From c46eb6dae309dd42bb66495e5562268fc250fff3 Mon Sep 17 00:00:00 2001 From: RedYetiDev <38299977+RedYetiDev@users.noreply.github.com> Date: Wed, 25 Sep 2024 15:07:57 -0400 Subject: [PATCH] lib: prefer logical assignment --- benchmark/_http-benchmarkers.js | 2 +- benchmark/common.js | 10 +++--- benchmark/es/defaultparams-bench.js | 4 +-- benchmark/perf_hooks/resourcetiming.js | 18 ++++------- benchmark/zlib/deflate.js | 2 +- benchmark/zlib/inflate.js | 2 +- eslint.config.mjs | 1 + lib/_http_agent.js | 12 ++----- lib/_http_client.js | 4 +-- lib/_http_server.js | 12 +++---- lib/_tls_common.js | 5 ++- lib/_tls_wrap.js | 2 +- lib/assert.js | 2 +- lib/async_hooks.js | 2 +- lib/child_process.js | 22 +++++-------- lib/dgram.js | 3 +- lib/events.js | 4 +-- lib/internal/assert.js | 5 +-- .../bootstrap/switches/is_not_main_thread.js | 3 +- lib/internal/child_process.js | 7 ++-- lib/internal/cluster/child.js | 4 +-- lib/internal/cluster/primary.js | 3 +- lib/internal/console/constructor.js | 6 ++-- lib/internal/crypto/cipher.js | 6 ++-- lib/internal/crypto/keys.js | 10 +++--- lib/internal/error_serdes.js | 8 ++--- lib/internal/fs/promises.js | 2 +- lib/internal/fs/sync_write_stream.js | 2 +- lib/internal/fs/utils.js | 5 +-- lib/internal/http2/core.js | 26 +++++---------- lib/internal/inspector_network_tracking.js | 8 ++--- lib/internal/modules/helpers.js | 3 +- lib/internal/process/per_thread.js | 7 ++-- lib/internal/process/warning.js | 4 +-- lib/internal/readline/interface.js | 2 +- lib/internal/source_map/source_map_cache.js | 4 +-- lib/internal/streams/duplex.js | 7 ++-- lib/internal/streams/pipeline.js | 9 ++---- lib/internal/streams/readable.js | 4 +-- lib/internal/test_runner/coverage.js | 14 ++++---- lib/internal/test_runner/mock/mock_timers.js | 8 ++--- lib/internal/test_runner/test.js | 2 +- lib/internal/test_runner/utils.js | 4 +-- lib/internal/util/inspect.js | 4 +-- lib/net.js | 8 ++--- lib/querystring.js | 4 +-- lib/readline.js | 3 +- lib/repl.js | 21 ++++++------ lib/timers.js | 6 ++-- lib/url.js | 14 ++++---- test/async-hooks/init-hooks.js | 2 +- test/async-hooks/verify-graph.js | 6 ++-- test/common/shared-lib-util.js | 2 +- test/common/wpt.js | 12 ++----- test/parallel/test-http-abort-queued.js | 2 +- .../test-http-host-header-ipv6-fail.js | 2 +- test/parallel/test-http-parser.js | 2 +- ...test-http2-create-client-secure-session.js | 2 +- .../test-perf-hooks-resourcetiming.js | 18 ++++------- test/parallel/test-stream-big-packet.js | 6 ++-- test/parallel/test-stream2-transform.js | 4 +-- test/parallel/test-tls-client-verify.js | 8 ++--- test/parallel/test-tls-ticket.js | 2 +- test/parallel/test-vm-cached-data.js | 3 +- test/parallel/test-zlib-random-byte-pipes.js | 8 ++--- tools/doc/common.mjs | 32 +++++++------------ tools/doc/generate.mjs | 2 +- tools/doc/html.mjs | 4 +-- tools/doc/json.mjs | 10 +++--- tools/doc/markdown.mjs | 10 +++--- tools/eslint-rules/no-unescaped-regexp-dot.js | 6 ++-- tools/license2rtf.mjs | 3 +- tools/lint-sh.mjs | 2 +- 73 files changed, 177 insertions(+), 301 deletions(-) diff --git a/benchmark/_http-benchmarkers.js b/benchmark/_http-benchmarkers.js index 4eba83eccb58f0..b9ef93c149f765 100644 --- a/benchmark/_http-benchmarkers.js +++ b/benchmark/_http-benchmarkers.js @@ -110,7 +110,7 @@ class TestDoubleBenchmarker { } create(options) { - process.env.duration = process.env.duration || options.duration || 5; + process.env.duration ||= options.duration || 5; const scheme = options.scheme || 'http'; const env = { diff --git a/benchmark/common.js b/benchmark/common.js index b4978e8e140b18..8da8bd71f3ac2f 100644 --- a/benchmark/common.js +++ b/benchmark/common.js @@ -113,8 +113,7 @@ class Benchmark { } const [, key, value] = match; if (configs[key] !== undefined) { - if (!cliOptions[key]) - cliOptions[key] = []; + cliOptions[key] ||= []; cliOptions[key].push( // Infer the type from the config object and parse accordingly typeof configs[key][0] === 'number' ? +value : value, @@ -177,10 +176,9 @@ class Benchmark { http(options, cb) { const http_options = { ...options }; - http_options.benchmarker = http_options.benchmarker || - this.config.benchmarker || - this.extra_options.benchmarker || - http_benchmarkers.default_http_benchmarker; + http_options.benchmarker ||= this.config.benchmarker || + this.extra_options.benchmarker || + http_benchmarkers.default_http_benchmarker; http_benchmarkers.run( http_options, (error, code, used_benchmarker, result, elapsed) => { if (cb) { diff --git a/benchmark/es/defaultparams-bench.js b/benchmark/es/defaultparams-bench.js index 4befe99177175b..1e42b0aed8a5cb 100644 --- a/benchmark/es/defaultparams-bench.js +++ b/benchmark/es/defaultparams-bench.js @@ -9,8 +9,8 @@ const bench = common.createBenchmark(main, { }); function oldStyleDefaults(x, y) { - x = x || 1; - y = y || 2; + x ||= 1; + y ||= 2; assert.strictEqual(x, 1); assert.strictEqual(y, 2); } diff --git a/benchmark/perf_hooks/resourcetiming.js b/benchmark/perf_hooks/resourcetiming.js index 69ee06c92cbd9f..e0fe90d657f78d 100644 --- a/benchmark/perf_hooks/resourcetiming.js +++ b/benchmark/perf_hooks/resourcetiming.js @@ -21,18 +21,12 @@ function createTimingInfo({ finalConnectionTimingInfo = null, }) { if (finalConnectionTimingInfo !== null) { - finalConnectionTimingInfo.domainLookupStartTime = - finalConnectionTimingInfo.domainLookupStartTime || 0; - finalConnectionTimingInfo.domainLookupEndTime = - finalConnectionTimingInfo.domainLookupEndTime || 0; - finalConnectionTimingInfo.connectionStartTime = - finalConnectionTimingInfo.connectionStartTime || 0; - finalConnectionTimingInfo.connectionEndTime = - finalConnectionTimingInfo.connectionEndTime || 0; - finalConnectionTimingInfo.secureConnectionStartTime = - finalConnectionTimingInfo.secureConnectionStartTime || 0; - finalConnectionTimingInfo.ALPNNegotiatedProtocol = - finalConnectionTimingInfo.ALPNNegotiatedProtocol || []; + finalConnectionTimingInfo.domainLookupStartTime ||= 0; + finalConnectionTimingInfo.domainLookupEndTime ||= 0; + finalConnectionTimingInfo.connectionStartTime ||= 0; + finalConnectionTimingInfo.connectionEndTime ||= 0; + finalConnectionTimingInfo.secureConnectionStartTime ||= 0; + finalConnectionTimingInfo.ALPNNegotiatedProtocol ||= []; } return { startTime, diff --git a/benchmark/zlib/deflate.js b/benchmark/zlib/deflate.js index ab9ff333224a0e..2f57df9b5e8d99 100644 --- a/benchmark/zlib/deflate.js +++ b/benchmark/zlib/deflate.js @@ -10,7 +10,7 @@ const bench = common.createBenchmark(main, { function main({ n, method, inputLen }) { // Default method value for testing. - method = method || 'deflate'; + method ||= 'deflate'; const chunk = Buffer.alloc(inputLen, 'a'); switch (method) { diff --git a/benchmark/zlib/inflate.js b/benchmark/zlib/inflate.js index a65b00f78a5059..e2e29755f5d483 100644 --- a/benchmark/zlib/inflate.js +++ b/benchmark/zlib/inflate.js @@ -10,7 +10,7 @@ const bench = common.createBenchmark(main, { function main({ n, method, inputLen }) { // Default method value for tests. - method = method || 'inflate'; + method ||= 'inflate'; const chunk = zlib.deflateSync(Buffer.alloc(inputLen, 'a')); let i = 0; diff --git a/eslint.config.mjs b/eslint.config.mjs index 2ba63203d8e1b9..f22bbc3bbd2f99 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -144,6 +144,7 @@ export default [ ignorePattern: '.*', }, }], + 'logical-assignment-operators': ['error', 'always', { enforceForIfStatements: true }], 'default-case-last': 'error', 'dot-notation': 'error', 'eqeqeq': ['error', 'smart'], diff --git a/lib/_http_agent.js b/lib/_http_agent.js index 7e5c224470cac4..fb20b4780ba332 100644 --- a/lib/_http_agent.js +++ b/lib/_http_agent.js @@ -246,9 +246,7 @@ Agent.prototype.addRequest = function addRequest(req, options, port/* legacy */, normalizeServerName(options, req); const name = this.getName(options); - if (!this.sockets[name]) { - this.sockets[name] = []; - } + this.sockets[name] ||= []; const freeSockets = this.freeSockets[name]; let socket; @@ -284,9 +282,7 @@ Agent.prototype.addRequest = function addRequest(req, options, port/* legacy */, } else { debug('wait for socket'); // We are over limit so we'll add it to the queue. - if (!this.requests[name]) { - this.requests[name] = []; - } + this.requests[name] ||= []; // Used to create sockets for pending requests from different origin req[kRequestOptions] = options; @@ -313,9 +309,7 @@ Agent.prototype.createSocket = function createSocket(req, options, cb) { const oncreate = once((err, s) => { if (err) return cb(err); - if (!this.sockets[name]) { - this.sockets[name] = []; - } + this.sockets[name] ||= []; this.sockets[name].push(s); this.totalSocketCount++; debug('sockets', name, this.sockets[name].length, this.totalSocketCount); diff --git a/lib/_http_client.js b/lib/_http_client.js index 750536dd06cac9..a0009cfb8f432b 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -347,8 +347,8 @@ function ClientRequest(input, options, cb) { opts = { ...optsWithoutSignal }; if (opts.socketPath) { opts.path = opts.socketPath; - } else if (opts.path) { - opts.path = undefined; + } else { + opts.path &&= undefined; } } if (typeof opts.createConnection === 'function') { diff --git a/lib/_http_server.js b/lib/_http_server.js index 6a0bcd75513b5c..fc44f34909611a 100644 --- a/lib/_http_server.js +++ b/lib/_http_server.js @@ -357,8 +357,7 @@ function writeHead(statusCode, reason, obj) { this.statusMessage = reason; } else { // writeHead(statusCode[, headers]) - if (!this.statusMessage) - this.statusMessage = STATUS_CODES[statusCode] || 'unknown'; + this.statusMessage ||= STATUS_CODES[statusCode] || 'unknown'; obj ??= reason; } this.statusCode = statusCode; @@ -510,9 +509,7 @@ function storeHTTPOptions(options) { function setupConnectionsTracking() { // Start connection handling - if (!this[kConnections]) { - this[kConnections] = new ConnectionsList(); - } + this[kConnections] ||= new ConnectionsList(); if (this[kConnectionsCheckingInterval]) { clearInterval(this[kConnectionsCheckingInterval]); @@ -923,8 +920,7 @@ function onParserExecuteCommon(server, socket, parser, state, ret, d) { const req = parser.incoming; debug('SERVER upgrade or connect', req.method); - if (!d) - d = parser.getCurrentBuffer(); + d ||= parser.getCurrentBuffer(); socket.removeListener('data', state.onData); socket.removeListener('end', state.onEnd); @@ -962,7 +958,7 @@ function onParserExecuteCommon(server, socket, parser, state, ret, d) { } function clearIncoming(req) { - req = req || this; + req ||= this; const parser = req.socket?.parser; // Reset the .incoming property so that the request object can be gc'ed. if (parser && parser.incoming === req) { diff --git a/lib/_tls_common.js b/lib/_tls_common.js index 362b8e41893c0e..66331d2d9999e9 100644 --- a/lib/_tls_common.js +++ b/lib/_tls_common.js @@ -57,7 +57,7 @@ const { } = require('internal/tls/secure-context'); function toV(which, v, def) { - if (v == null) v = def; + v ??= def; if (v === 'TLSv1') return TLS1_VERSION; if (v === 'TLSv1.1') return TLS1_1_VERSION; if (v === 'TLSv1.2') return TLS1_2_VERSION; @@ -94,8 +94,7 @@ function SecureContext(secureProtocol, secureOptions, minVersion, maxVersion) { } function createSecureContext(options) { - if (!options) options = kEmptyObject; - + options ||= kEmptyObject; const { honorCipherOrder, minVersion, diff --git a/lib/_tls_wrap.js b/lib/_tls_wrap.js index 6818515d6ab684..c44097a31a0a01 100644 --- a/lib/_tls_wrap.js +++ b/lib/_tls_wrap.js @@ -1328,7 +1328,7 @@ function Server(options, listener) { listener = options; options = kEmptyObject; } else if (options == null || typeof options === 'object') { - options = options ?? kEmptyObject; + options ??= kEmptyObject; } else { throw new ERR_INVALID_ARG_TYPE('options', 'Object', options); } diff --git a/lib/assert.js b/lib/assert.js index d121d2718dfe95..2a65457b39387e 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -750,7 +750,7 @@ function internalMatch(string, regexp, message, fn) { const generatedMessage = !message; // 'The input was expected to not match the regular expression ' + - message = message || (typeof string !== 'string' ? + message ||= (typeof string !== 'string' ? 'The "string" argument must be of type string. Received type ' + `${typeof string} (${inspect(string)})` : (match ? diff --git a/lib/async_hooks.js b/lib/async_hooks.js index f6d52a83fd004a..5e381d5b3c8a28 100644 --- a/lib/async_hooks.js +++ b/lib/async_hooks.js @@ -269,7 +269,7 @@ class AsyncResource { } static bind(fn, type, thisArg) { - type = type || fn.name; + type ||= fn.name; return (new AsyncResource(type || 'bound-anonymous-fn')).bind(fn, thisArg); } } diff --git a/lib/child_process.js b/lib/child_process.js index 51fc6fe995d3cf..0a6539589ebfb6 100644 --- a/lib/child_process.js +++ b/lib/child_process.js @@ -138,7 +138,7 @@ function fork(modulePath, args = [], options) { validateObject(options, 'options'); } options = { __proto__: null, ...options, shell: false }; - options.execPath = options.execPath || process.execPath; + options.execPath ||= process.execPath; validateArgumentNullCheck(options.execPath, 'options.execPath'); // Prepare arguments for fork: @@ -272,9 +272,7 @@ function normalizeExecFileArgs(file, args, options, callback) { args = null; } - if (args == null) { - args = []; - } + args ??= []; if (typeof options === 'function') { callback = options; @@ -282,9 +280,7 @@ function normalizeExecFileArgs(file, args, options, callback) { validateObject(options, 'options'); } - if (options == null) { - options = kEmptyObject; - } + options ??= kEmptyObject; if (callback != null) { validateFunction(callback, 'callback'); @@ -415,13 +411,11 @@ function execFile(file, args, options, callback) { if (args?.length) cmd += ` ${ArrayPrototypeJoin(args, ' ')}`; - if (!ex) { - ex = genericNodeError(`Command failed: ${cmd}\n${stderr}`, { - code: code < 0 ? getSystemErrorName(code) : code, - killed: child.killed || killed, - signal: signal, - }); - } + ex ||= genericNodeError(`Command failed: ${cmd}\n${stderr}`, { + code: code < 0 ? getSystemErrorName(code) : code, + killed: child.killed || killed, + signal: signal, + }); ex.cmd = cmd; callback(ex, stdout, stderr); diff --git a/lib/dgram.js b/lib/dgram.js index 84b8708f701ed0..f6089aa747d45a 100644 --- a/lib/dgram.js +++ b/lib/dgram.js @@ -94,8 +94,7 @@ const SEND_BUFFER = false; // Lazily loaded let _cluster = null; function lazyLoadCluster() { - if (!_cluster) _cluster = require('cluster'); - return _cluster; + return _cluster ??= require('cluster'); } function Socket(type, listener) { diff --git a/lib/events.js b/lib/events.js index 256dd580e159bd..78429248f6e2fd 100644 --- a/lib/events.js +++ b/lib/events.js @@ -337,7 +337,7 @@ EventEmitter.init = function(opts) { this[kShapeMode] = true; } - this._maxListeners = this._maxListeners || undefined; + this._maxListeners ||= undefined; if (opts?.captureRejections) { @@ -457,7 +457,7 @@ EventEmitter.prototype.emit = function emit(type, ...args) { if (events !== undefined) { if (doError && events[kErrorMonitor] !== undefined) this.emit(kErrorMonitor, ...args); - doError = (doError && events.error === undefined); + doError &&= events.error === undefined; } else if (!doError) return false; diff --git a/lib/internal/assert.js b/lib/internal/assert.js index 0f52faab4bcf53..32c696edf6b076 100644 --- a/lib/internal/assert.js +++ b/lib/internal/assert.js @@ -2,10 +2,7 @@ let error; function lazyError() { - if (!error) { - error = require('internal/errors').codes.ERR_INTERNAL_ASSERTION; - } - return error; + return error ??= require('internal/errors').codes.ERR_INTERNAL_ASSERTION; } function assert(value, message) { diff --git a/lib/internal/bootstrap/switches/is_not_main_thread.js b/lib/internal/bootstrap/switches/is_not_main_thread.js index c4c2a7cb280b0d..03aa7c3ebe12f2 100644 --- a/lib/internal/bootstrap/switches/is_not_main_thread.js +++ b/lib/internal/bootstrap/switches/is_not_main_thread.js @@ -37,8 +37,7 @@ const { let workerStdio; function lazyWorkerStdio() { - if (!workerStdio) workerStdio = createWorkerStdio(); - return workerStdio; + return workerStdio ??= createWorkerStdio(); } function getStdout() { return lazyWorkerStdio().stdout; } diff --git a/lib/internal/child_process.js b/lib/internal/child_process.js index ab6872e4f89243..1b769993a719ab 100644 --- a/lib/internal/child_process.js +++ b/lib/internal/child_process.js @@ -852,8 +852,7 @@ function setupChannel(target, channel, serializationMode) { if (err === 0) { if (handle) { - if (!this._handleQueue) - this._handleQueue = []; + this._handleQueue ||= []; if (obj?.postSend) obj.postSend(message, handle, options, callback, target); } @@ -1009,9 +1008,7 @@ function getValidStdio(stdio, sync) { } // Defaults - if (stdio == null) { - stdio = i < 3 ? 'pipe' : 'ignore'; - } + stdio ??= i < 3 ? 'pipe' : 'ignore'; if (stdio === 'ignore') { ArrayPrototypePush(acc, { type: 'ignore' }); diff --git a/lib/internal/cluster/child.js b/lib/internal/cluster/child.js index bee474567b6351..a8586202484beb 100644 --- a/lib/internal/cluster/child.js +++ b/lib/internal/cluster/child.js @@ -167,9 +167,7 @@ function rr(message, { indexesKey, index }, cb) { let fakeHandle = null; function ref() { - if (!fakeHandle) { - fakeHandle = setInterval(noop, TIMEOUT_MAX); - } + fakeHandle ||= setInterval(noop, TIMEOUT_MAX); } function unref() { diff --git a/lib/internal/cluster/primary.js b/lib/internal/cluster/primary.js index 630704da8fe614..af17d39de44964 100644 --- a/lib/internal/cluster/primary.js +++ b/lib/internal/cluster/primary.js @@ -301,8 +301,7 @@ function queryServer(worker, message) { handles.set(key, handle); } - if (!handle.data) - handle.data = message.data; + handle.data ||= message.data; // Set custom server data handle.add(worker, (errno, reply, handle) => { diff --git a/lib/internal/console/constructor.js b/lib/internal/console/constructor.js index c892b91919da75..6d01b8c3d7c181 100644 --- a/lib/internal/console/constructor.js +++ b/lib/internal/console/constructor.js @@ -203,8 +203,7 @@ ObjectDefineProperties(Console.prototype, { enumerable: false, configurable: true, get() { - if (!stdout) stdout = object.stdout; - return stdout; + return stdout ||= object.stdout; }, set(value) { stdout = value; }, }, @@ -213,8 +212,7 @@ ObjectDefineProperties(Console.prototype, { enumerable: false, configurable: true, get() { - if (!stderr) { stderr = object.stderr; } - return stderr; + return stderr ||= object.stderr; }, set(value) { stderr = value; }, }, diff --git a/lib/internal/crypto/cipher.js b/lib/internal/crypto/cipher.js index 6f47b47f90ea4d..c303e2fa311a0e 100644 --- a/lib/internal/crypto/cipher.js +++ b/lib/internal/crypto/cipher.js @@ -92,7 +92,7 @@ const privateDecrypt = rsaFunctionFor(_privateDecrypt, RSA_PKCS1_OAEP_PADDING, function getDecoder(decoder, encoding) { const normalizedEncoding = normalizeEncoding(encoding); - decoder = decoder || new StringDecoder(encoding); + decoder ||= new StringDecoder(encoding); if (decoder.encoding !== normalizedEncoding) { if (normalizedEncoding === undefined) { throw new ERR_UNKNOWN_ENCODING(encoding); @@ -303,8 +303,8 @@ function getCipherInfo(nameOrNid, options) { const ret = _getCipherInfo({}, nameOrNid, keyLength, ivLength); if (ret !== undefined) { - if (ret.name) ret.name = StringPrototypeToLowerCase(ret.name); - if (ret.type) ret.type = StringPrototypeToLowerCase(ret.type); + ret.name &&= StringPrototypeToLowerCase(ret.name); + ret.type &&= StringPrototypeToLowerCase(ret.type); } return ret; } diff --git a/lib/internal/crypto/keys.js b/lib/internal/crypto/keys.js index e7d2275ee1a9fa..e1090f92e59a30 100644 --- a/lib/internal/crypto/keys.js +++ b/lib/internal/crypto/keys.js @@ -191,8 +191,7 @@ const { } get asymmetricKeyType() { - return this[kAsymmetricKeyType] || - (this[kAsymmetricKeyType] = this[kHandle].getAsymmetricKeyType()); + return this[kAsymmetricKeyType] ||= this[kHandle].getAsymmetricKeyType(); } get asymmetricKeyDetails() { @@ -201,10 +200,9 @@ const { case 'rsa-pss': case 'dsa': case 'ec': - return this[kAsymmetricKeyDetails] || - (this[kAsymmetricKeyDetails] = normalizeKeyDetails( - this[kHandle].keyDetail({}), - )); + return this[kAsymmetricKeyDetails] ||= normalizeKeyDetails( + this[kHandle].keyDetail({}), + ); default: return {}; } diff --git a/lib/internal/error_serdes.js b/lib/internal/error_serdes.js index e53291c6b770fc..a1072c2fe72f53 100644 --- a/lib/internal/error_serdes.js +++ b/lib/internal/error_serdes.js @@ -103,15 +103,13 @@ function GetName(object) { let internalUtilInspect; function inspect(...args) { - if (!internalUtilInspect) { - internalUtilInspect = require('internal/util/inspect'); - } + internalUtilInspect ??= require('internal/util/inspect'); return internalUtilInspect.inspect(...args); } let serialize; function serializeError(error) { - if (!serialize) serialize = require('v8').serialize; + serialize ??= require('v8').serialize; if (typeof error === 'symbol') { return Buffer.from(StringFromCharCode(kInspectedSymbol) + inspect(error), 'utf8'); } @@ -157,7 +155,7 @@ function fromBuffer(error) { let deserialize; function deserializeError(error) { - if (!deserialize) deserialize = require('v8').deserialize; + deserialize ??= require('v8').deserialize; switch (error[0]) { case kSerializedError: { const { constructor, properties } = deserialize(error.subarray(1)); diff --git a/lib/internal/fs/promises.js b/lib/internal/fs/promises.js index fd57191ef9869f..2a91865c8b0542 100644 --- a/lib/internal/fs/promises.js +++ b/lib/internal/fs/promises.js @@ -1223,7 +1223,7 @@ function isCustomIterable(obj) { async function appendFile(path, data, options) { options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'a' }); options = copyObject(options); - options.flag = options.flag || 'a'; + options.flag ||= 'a'; return writeFile(path, data, options); } diff --git a/lib/internal/fs/sync_write_stream.js b/lib/internal/fs/sync_write_stream.js index f8fbade88393b4..5ce4f1883b905d 100644 --- a/lib/internal/fs/sync_write_stream.js +++ b/lib/internal/fs/sync_write_stream.js @@ -12,7 +12,7 @@ const { closeSync, writeSync } = require('fs'); function SyncWriteStream(fd, options) { ReflectApply(Writable, this, [{ autoDestroy: true }]); - options = options || kEmptyObject; + options ||= kEmptyObject; this.fd = fd; this.readable = false; diff --git a/lib/internal/fs/utils.js b/lib/internal/fs/utils.js index 34634123fa84f0..d34e2054cba46e 100644 --- a/lib/internal/fs/utils.js +++ b/lib/internal/fs/utils.js @@ -147,10 +147,7 @@ const kMaxUserId = 2 ** 32 - 1; let fs; function lazyLoadFs() { - if (!fs) { - fs = require('fs'); - } - return fs; + return fs ??= require('fs'); } function assertEncoding(encoding) { diff --git a/lib/internal/http2/core.js b/lib/internal/http2/core.js index 923db9ad1b5b1e..6135b98cfff2f3 100644 --- a/lib/internal/http2/core.js +++ b/lib/internal/http2/core.js @@ -1279,10 +1279,7 @@ class Http2Session extends EventEmitter { setupFn(); } - if (!this[kNativeFields]) { - this[kNativeFields] = trackAssignmentsTypedArray( - new Uint8Array(kSessionUint8FieldCount)); - } + this[kNativeFields] ||= trackAssignmentsTypedArray(new Uint8Array(kSessionUint8FieldCount)); this.on('newListener', sessionListenerAdded); this.on('removeListener', sessionListenerRemoved); @@ -2448,10 +2445,7 @@ function processHeaders(oldHeaders, options) { headers[HTTP2_HEADER_STATUS] | 0 || HTTP_STATUS_OK; if (options.sendDate == null || options.sendDate) { - if (headers[HTTP2_HEADER_DATE] === null || - headers[HTTP2_HEADER_DATE] === undefined) { - headers[HTTP2_HEADER_DATE] = utcDate(); - } + headers[HTTP2_HEADER_DATE] ??= utcDate(); } // This is intentionally stricter than the HTTP/1 implementation, which @@ -3123,15 +3117,11 @@ function initializeOptions(options) { // Used only with allowHTTP1 - options.Http1IncomingMessage = options.Http1IncomingMessage || - http.IncomingMessage; - options.Http1ServerResponse = options.Http1ServerResponse || - http.ServerResponse; - - options.Http2ServerRequest = options.Http2ServerRequest || - Http2ServerRequest; - options.Http2ServerResponse = options.Http2ServerResponse || - Http2ServerResponse; + options.Http1IncomingMessage ||= http.IncomingMessage; + options.Http1ServerResponse ||= http.ServerResponse; + + options.Http2ServerRequest ||= Http2ServerRequest; + options.Http2ServerResponse ||= Http2ServerResponse; return options; } @@ -3421,7 +3411,7 @@ function getUnpackedSettings(buf, options = kEmptyObject) { settings.enableConnectProtocol = value !== 0; break; default: - if (!settings.customSettings) settings.customSettings = {}; + settings.customSettings ||= {}; settings.customSettings[id] = value; } offset += 4; diff --git a/lib/internal/inspector_network_tracking.js b/lib/internal/inspector_network_tracking.js index df3d2e5bf8e539..de325baf77eb42 100644 --- a/lib/internal/inspector_network_tracking.js +++ b/lib/internal/inspector_network_tracking.js @@ -86,12 +86,8 @@ function onClientResponseFinish({ request, response }) { } function enable() { - if (!dc) { - dc = require('diagnostics_channel'); - } - if (!Network) { - Network = require('inspector').Network; - } + dc ??= require('diagnostics_channel'); + Network ??= require('inspector').Network; dc.subscribe('http.client.request.start', onClientRequestStart); dc.subscribe('http.client.request.error', onClientRequestError); dc.subscribe('http.client.response.finish', onClientResponseFinish); diff --git a/lib/internal/modules/helpers.js b/lib/internal/modules/helpers.js index 643f24ebc87814..826a89aba7e8fb 100644 --- a/lib/internal/modules/helpers.js +++ b/lib/internal/modules/helpers.js @@ -120,8 +120,7 @@ let $Module = null; * Import the Module class on first use. */ function lazyModule() { - $Module = $Module || require('internal/modules/cjs/loader').Module; - return $Module; + return $Module ??= require('internal/modules/cjs/loader').Module; } /** diff --git a/lib/internal/process/per_thread.js b/lib/internal/process/per_thread.js index 506e7ee7ba2592..9995dadfc648eb 100644 --- a/lib/internal/process/per_thread.js +++ b/lib/internal/process/per_thread.js @@ -208,7 +208,7 @@ function wrapProcessMethods(binding) { // it's monkey-patched by tests. err = process._kill(pid, sig); } else { - sig = sig || 'SIGTERM'; + sig ||= 'SIGTERM'; if (constants[sig]) { err = process._kill(pid, constants[sig]); } else { @@ -410,10 +410,7 @@ let traceEventsAsyncHook; // Dynamically enable/disable the traceEventsAsyncHook function toggleTraceCategoryState(asyncHooksEnabled) { if (asyncHooksEnabled) { - if (!traceEventsAsyncHook) { - traceEventsAsyncHook = - require('internal/trace_events_async_hooks').createHook(); - } + traceEventsAsyncHook ||= require('internal/trace_events_async_hooks').createHook(); traceEventsAsyncHook.enable(); } else if (traceEventsAsyncHook) { traceEventsAsyncHook.disable(); diff --git a/lib/internal/process/warning.js b/lib/internal/process/warning.js index 364e88d27769e5..6ca624abddf76c 100644 --- a/lib/internal/process/warning.js +++ b/lib/internal/process/warning.js @@ -52,9 +52,7 @@ function lazyOption() { // so use console.error. let error; function writeOut(message) { - if (!error) { - error = require('internal/console/global').error; - } + error ??= require('internal/console/global').error; error(message); } diff --git a/lib/internal/readline/interface.js b/lib/internal/readline/interface.js index aaa1dea7a8cbcd..b2ab2c00794f75 100644 --- a/lib/internal/readline/interface.js +++ b/lib/internal/readline/interface.js @@ -1054,7 +1054,7 @@ class Interface extends InterfaceConstructor { // Handle a write from the tty [kTtyWrite](s, key) { const previousKey = this[kPreviousKey]; - key = key || kEmptyObject; + key ||= kEmptyObject; this[kPreviousKey] = key; if (!key.meta || key.name !== 'y') { diff --git a/lib/internal/source_map/source_map_cache.js b/lib/internal/source_map/source_map_cache.js index b24ad24438441f..dfb42f83f6f1b1 100644 --- a/lib/internal/source_map/source_map_cache.js +++ b/lib/internal/source_map/source_map_cache.js @@ -338,9 +338,7 @@ function findSourceMap(sourceURL) { if (RegExpPrototypeExec(kLeadingProtocol, sourceURL) === null) { sourceURL = pathToFileURL(sourceURL).href; } - if (!SourceMap) { - SourceMap = require('internal/source_map/source_map').SourceMap; - } + SourceMap ??= require('internal/source_map/source_map').SourceMap; const entry = getModuleSourceMapCache().get(sourceURL) ?? generatedSourceMapCache.get(sourceURL); if (entry === undefined) { return undefined; diff --git a/lib/internal/streams/duplex.js b/lib/internal/streams/duplex.js index 6892150c49f659..713322c0f4aef9 100644 --- a/lib/internal/streams/duplex.js +++ b/lib/internal/streams/duplex.js @@ -54,8 +54,7 @@ ObjectSetPrototypeOf(Duplex, Readable); // Allow the keys array to be GC'ed. for (let i = 0; i < keys.length; i++) { const method = keys[i]; - if (!Duplex.prototype[method]) - Duplex.prototype[method] = Writable.prototype[method]; + Duplex.prototype[method] ||= Writable.prototype[method]; } } @@ -199,8 +198,6 @@ Duplex.toWeb = function(duplex) { let duplexify; Duplex.from = function(body) { - if (!duplexify) { - duplexify = require('internal/streams/duplexify'); - } + duplexify ??= require('internal/streams/duplexify'); return duplexify(body, 'body'); }; diff --git a/lib/internal/streams/pipeline.js b/lib/internal/streams/pipeline.js index 4531cf06aa2277..96897477ca2520 100644 --- a/lib/internal/streams/pipeline.js +++ b/lib/internal/streams/pipeline.js @@ -87,10 +87,7 @@ function makeAsyncIterable(val) { } async function* fromReadable(val) { - if (!Readable) { - Readable = require('internal/streams/readable'); - } - + Readable ??= require('internal/streams/readable'); yield* Readable.prototype[SymbolAsyncIterator].call(val); } @@ -319,9 +316,7 @@ function pipelineImpl(streams, callback, opts) { 'AsyncIterable', `transform[${i - 1}]`, ret); } } else { - if (!PassThrough) { - PassThrough = require('internal/streams/passthrough'); - } + PassThrough ??= require('internal/streams/passthrough'); // If the last argument to pipeline is not a stream // we must create a proxy stream so that pipeline(...) diff --git a/lib/internal/streams/readable.js b/lib/internal/streams/readable.js index 5a6fe1db000f5c..3079474b026f52 100644 --- a/lib/internal/streams/readable.js +++ b/lib/internal/streams/readable.js @@ -412,7 +412,7 @@ function readableAddChunkUnshiftByteMode(stream, state, chunk, encoding) { } if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; + encoding ||= state.defaultEncoding; if (state.encoding !== encoding) { if (state.encoding) { // When unshifting, if state.encoding is set, we have to save @@ -468,7 +468,7 @@ function readableAddChunkPushByteMode(stream, state, chunk, encoding) { } if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; + encoding ||= state.defaultEncoding; if (state.encoding !== encoding) { chunk = Buffer.from(chunk, encoding); encoding = ''; diff --git a/lib/internal/test_runner/coverage.js b/lib/internal/test_runner/coverage.js index 1b5ba7912dcb7d..3e4a27b929b747 100644 --- a/lib/internal/test_runner/coverage.js +++ b/lib/internal/test_runner/coverage.js @@ -489,14 +489,12 @@ function setupCoverage(options) { let originalCoverageDirectory = process.env.NODE_V8_COVERAGE; const cwd = process.cwd(); - if (originalCoverageDirectory) { - // NODE_V8_COVERAGE was already specified. Convert it to an absolute path - // and store it for later. The test runner will use a temporary directory - // so that no preexisting coverage files interfere with the results of the - // coverage report. Then, once the coverage is computed, move the coverage - // files back to the original NODE_V8_COVERAGE directory. - originalCoverageDirectory = resolve(cwd, originalCoverageDirectory); - } + // If NODE_V8_COVERAGE was already specified, convert it to an absolute path + // and store it for later. The test runner will use a temporary directory + // so that no preexisting coverage files interfere with the results of the + // coverage report. Then, once the coverage is computed, move the coverage + // files back to the original NODE_V8_COVERAGE directory. + originalCoverageDirectory &&= resolve(cwd, originalCoverageDirectory); const coverageDirectory = mkdtempSync(join(tmpdir(), 'node-coverage-')); const enabled = setupCoverageHooks(coverageDirectory); diff --git a/lib/internal/test_runner/mock/mock_timers.js b/lib/internal/test_runner/mock/mock_timers.js index fa91c9759ecc15..1eed72b4b977f6 100644 --- a/lib/internal/test_runner/mock/mock_timers.js +++ b/lib/internal/test_runner/mock/mock_timers.js @@ -688,13 +688,9 @@ class MockTimers { throw new ERR_INVALID_ARG_VALUE('now', internalOptions.now, `epoch must be a positive integer received ${internalOptions.now}`); } - if (!internalOptions.now) { - internalOptions.now = 0; - } + internalOptions.now ||= 0; - if (!internalOptions.apis) { - internalOptions.apis = SUPPORTED_APIS; - } + internalOptions.apis ||= SUPPORTED_APIS; validateStringArray(internalOptions.apis, 'options.apis'); // Check that the timers passed are supported diff --git a/lib/internal/test_runner/test.js b/lib/internal/test_runner/test.js index 4331079f74e95a..20e86ca366a9d0 100644 --- a/lib/internal/test_runner/test.js +++ b/lib/internal/test_runner/test.js @@ -653,7 +653,7 @@ class Test extends AsyncResource { // - Only called if there are results to report in the correct order. // - Guaranteed to only be called a maximum of once per call to // processReadySubtestRange(). - canSend = canSend || this.isClearToSend(); + canSend ||= this.isClearToSend(); if (!canSend) { return; diff --git a/lib/internal/test_runner/utils.js b/lib/internal/test_runner/utils.js index 67ce601c1dfe5f..691cd6ce4785fc 100644 --- a/lib/internal/test_runner/utils.js +++ b/lib/internal/test_runner/utils.js @@ -424,9 +424,7 @@ function buildFileTree(summary) { let current = tree; ArrayPrototypeForEach(parts, (part, index) => { - if (!current[part]) { - current[part] = { __proto__: null }; - } + current[part] ||= { __proto__: null }; current = current[part]; // If this is the last part, add the file to the tree if (index === parts.length - 1) { diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index c10db2954db662..df90ed34d51d73 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -1286,7 +1286,7 @@ function improveStack(stack, constructor, name, tag) { RegExpPrototypeExec(/^([a-z_A-Z0-9-]*Error)$/, stack); fallback = (start?.[1]) || ''; len = fallback.length; - fallback = fallback || 'Error'; + fallback ||= 'Error'; } const prefix = StringPrototypeSlice(getPrefix(constructor, tag, fallback), 0, -1); if (name !== prefix) { @@ -1941,7 +1941,7 @@ function formatProperty(ctx, value, recurseTimes, key, type, desc, original = value) { let name, str; let extra = ' '; - desc = desc || ObjectGetOwnPropertyDescriptor(value, key) || + desc ||= ObjectGetOwnPropertyDescriptor(value, key) || { value: value[key], enumerable: true }; if (desc.value !== undefined) { const diff = (ctx.compact !== true || type !== kObjectType) ? 2 : 3; diff --git a/lib/net.js b/lib/net.js index 604ba648754a2a..5a6f53aede4838 100644 --- a/lib/net.js +++ b/lib/net.js @@ -1045,10 +1045,10 @@ function internalConnect( if (localAddress || localPort) { if (addressType === 4) { - localAddress = localAddress || DEFAULT_IPV4_ADDR; + localAddress ||= DEFAULT_IPV4_ADDR; err = self._handle.bind(localAddress, localPort); } else { // addressType === 6 - localAddress = localAddress || DEFAULT_IPV6_ADDR; + localAddress ||= DEFAULT_IPV6_ADDR; err = self._handle.bind6(localAddress, localPort, flags); } debug('connect: binding to localAddress: %s and localPort: %d (addressType: %d)', @@ -1445,9 +1445,7 @@ function lookupAndConnectMultiple( return; } if (isIP(ip) && (addressType === 4 || addressType === 6)) { - if (!destinations) { - destinations = addressType === 6 ? { 6: 0, 4: 1 } : { 4: 0, 6: 1 }; - } + destinations ||= addressType === 6 ? { 6: 0, 4: 1 } : { 4: 0, 6: 1 }; const destination = destinations[addressType]; diff --git a/lib/querystring.js b/lib/querystring.js index c4cbca0c5a2733..576e0bafdc2810 100644 --- a/lib/querystring.js +++ b/lib/querystring.js @@ -225,8 +225,8 @@ function encodeStringifiedCustom(v, encode) { * @returns {string} */ function stringify(obj, sep, eq, options) { - sep = sep || '&'; - eq = eq || '='; + sep ||= '&'; + eq ||= '='; let encode = QueryString.escape; if (options && typeof options.encodeURIComponent === 'function') { diff --git a/lib/readline.js b/lib/readline.js index e3ae952648fcec..e0e57e9a107a20 100644 --- a/lib/readline.js +++ b/lib/readline.js @@ -465,8 +465,7 @@ Interface.prototype._moveCursor = _Interface.prototype[kMoveCursor]; Interface.prototype._ttyWrite = _Interface.prototype[kTtyWrite]; function _ttyWriteDumb(s, key) { - key = key || kEmptyObject; - + key ||= kEmptyObject; if (key.name === 'escape') return; if (this[kSawReturnAt] && key.name !== 'enter') diff --git a/lib/repl.js b/lib/repl.js index 005da4ee915625..bbdf3e916daeb6 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -286,10 +286,9 @@ function REPLServer(prompt, if (!options.input && !options.output) { // Legacy API, passing a 'stream'/'socket' option. - if (!stream) { - // Use stdin and stdout as the default streams if none were given. - stream = process; - } + // Use stdin and stdout as the default streams if none were given. + stream ||= process; + // We're given a duplex readable/writable Stream, like a `net.Socket` // or a custom object with 2 streams, or the `process` object. options.input = stream.stdin || stream; @@ -398,7 +397,7 @@ function REPLServer(prompt, `${sep}(.*)${sep}(.*)${sep}(.*)${sep}(.*)` + `${sep}(.*)$`); - eval_ = eval_ || defaultEval; + eval_ ||= defaultEval; const self = this; @@ -879,7 +878,7 @@ function REPLServer(prompt, self.on('line', function onLine(cmd) { debug('line %j', cmd); - cmd = cmd || ''; + cmd ||= ''; sawSIGINT = false; if (self.editorMode) { @@ -1007,7 +1006,7 @@ function REPLServer(prompt, // Wrap readline tty to enable editor mode and pausing. const ttyWrite = FunctionPrototypeBind(self._ttyWrite, self); self._ttyWrite = (d, key) => { - key = key || {}; + key ||= {}; if (paused && !(self.breakEvalOnSigint && key.ctrl && key.name === 'c')) { ArrayPrototypePush(pausedBuffer, ['key', [d, key], self.isCompletionEnabled]); @@ -1553,9 +1552,7 @@ function complete(line, callback) { ArrayPrototypeMap(group, (member) => `${expr}${member}`)); }); - if (filter) { - filter = `${expr}${filter}`; - } + filter &&= `${expr}${filter}`; } completionGroupsLoaded(); @@ -1645,8 +1642,8 @@ REPLServer.prototype.defineCommand = function(keyword, cmd) { // sufficient anymore. function _memory(cmd) { const self = this; - self.lines = self.lines || []; - self.lines.level = self.lines.level || []; + self.lines ||= []; + self.lines.level ||= []; // Save the line so I can do magic later if (cmd) { diff --git a/lib/timers.js b/lib/timers.js index a0e58810752035..3a4da5347535b8 100644 --- a/lib/timers.js +++ b/lib/timers.js @@ -170,8 +170,7 @@ ObjectDefineProperty(setTimeout, customPromisify, { __proto__: null, enumerable: true, get() { - if (!timersPromises) - timersPromises = require('timers/promises'); + timersPromises ??= require('timers/promises'); return timersPromises.setTimeout; }, }); @@ -309,8 +308,7 @@ ObjectDefineProperty(setImmediate, customPromisify, { __proto__: null, enumerable: true, get() { - if (!timersPromises) - timersPromises = require('timers/promises'); + timersPromises ??= require('timers/promises'); return timersPromises.setImmediate; }, }); diff --git a/lib/url.js b/lib/url.js index a2dc57e8bd24e4..ef1b1a23d9a5c8 100644 --- a/lib/url.js +++ b/lib/url.js @@ -790,8 +790,8 @@ Url.prototype.resolveObject = function resolveObject(relative) { !hostlessProtocol.has(relative.protocol)) { const relPath = (relative.pathname || '').split('/'); while (relPath.length && !(relative.host = relPath.shift())); - if (!relative.host) relative.host = ''; - if (!relative.hostname) relative.hostname = ''; + relative.host ||= ''; + relative.hostname ||= ''; if (relPath[0] !== '') relPath.unshift(''); if (relPath.length < 2) relPath.unshift(''); result.pathname = relPath.join('/'); @@ -810,7 +810,7 @@ Url.prototype.resolveObject = function resolveObject(relative) { const s = result.search || ''; result.path = p + s; } - result.slashes = result.slashes || relative.slashes; + result.slashes ||= relative.slashes; result.href = result.format(); return result; } @@ -850,7 +850,7 @@ Url.prototype.resolveObject = function resolveObject(relative) { } relative.host = null; } - mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + mustEndAbs &&= (relPath[0] === '' || srcPath[0] === ''); } if (isRelAbs) { @@ -871,7 +871,7 @@ Url.prototype.resolveObject = function resolveObject(relative) { } else if (relPath.length) { // it's relative // throw away the existing file, and take the new path instead. - if (!srcPath) srcPath = []; + srcPath ||= []; srcPath.pop(); srcPath = srcPath.concat(relPath); result.search = relative.search; @@ -974,7 +974,7 @@ Url.prototype.resolveObject = function resolveObject(relative) { } } - mustEndAbs = mustEndAbs || (result.host && srcPath.length); + mustEndAbs ||= (result.host && srcPath.length); if (mustEndAbs && !isAbsolute) { srcPath.unshift(''); @@ -993,7 +993,7 @@ Url.prototype.resolveObject = function resolveObject(relative) { (result.search ? result.search : ''); } result.auth = relative.auth || result.auth; - result.slashes = result.slashes || relative.slashes; + result.slashes ||= relative.slashes; result.href = result.format(); return result; }; diff --git a/test/async-hooks/init-hooks.js b/test/async-hooks/init-hooks.js index 5b891879c0ce51..2206ab31eba75f 100644 --- a/test/async-hooks/init-hooks.js +++ b/test/async-hooks/init-hooks.js @@ -146,7 +146,7 @@ class ActivityCollector { _stamp(h, hook) { if (h == null) return; - if (h[hook] == null) h[hook] = []; + h[hook] ??= []; const time = process.hrtime(this._start); h[hook].push((time[0] * 1e9) + time[1]); } diff --git a/test/async-hooks/verify-graph.js b/test/async-hooks/verify-graph.js index 27cd4633920a3c..776ec5b2283969 100644 --- a/test/async-hooks/verify-graph.js +++ b/test/async-hooks/verify-graph.js @@ -69,7 +69,7 @@ module.exports = function verifyGraph(hooks, graph) { activities.forEach(processActivity); function processActivity(x) { - if (!typeSeen[x.type]) typeSeen[x.type] = 0; + typeSeen[x.type] ||= 0; typeSeen[x.type]++; const node = findInGraph(graph, x.type, typeSeen[x.type]); @@ -102,7 +102,7 @@ module.exports = function verifyGraph(hooks, graph) { // Verify that all expected types are present (but more/others are allowed) const expTypes = { __proto__: null }; for (let i = 0; i < graph.length; i++) { - if (expTypes[graph[i].type] == null) expTypes[graph[i].type] = 0; + expTypes[graph[i].type] ??= 0; expTypes[graph[i].type]++; } @@ -129,7 +129,7 @@ module.exports.printGraph = function printGraph(hooks) { function processNode(x) { const key = x.type.replace(/WRAP/, '').toLowerCase(); - if (!ids[key]) ids[key] = 1; + ids[key] ||= 1; const id = `${key}:${ids[key]++}`; uidtoid[x.uid] = id; const triggerAsyncId = uidtoid[x.triggerAsyncId] || null; diff --git a/test/common/shared-lib-util.js b/test/common/shared-lib-util.js index b5d947a266cfea..5c2832cda9473f 100644 --- a/test/common/shared-lib-util.js +++ b/test/common/shared-lib-util.js @@ -13,7 +13,7 @@ function addLibraryPath(env) { return; } - env = env || process.env; + env ||= process.env; env.LD_LIBRARY_PATH = (env.LD_LIBRARY_PATH ? env.LD_LIBRARY_PATH + path.delimiter : '') + diff --git a/test/common/wpt.js b/test/common/wpt.js index 0c8805d541286e..3ead9cb23b9c46 100644 --- a/test/common/wpt.js +++ b/test/common/wpt.js @@ -878,22 +878,16 @@ class WPTRunner { addTestResult(spec, item) { let result = this.results[spec.filename]; - if (!result) { - result = this.results[spec.filename] = {}; - } + result ||= this.results[spec.filename] = {}; if (item.status === kSkip) { // { filename: { skip: 'reason' } } result[kSkip] = item.reason; } else { // { filename: { fail: { expected: [ ... ], // unexpected: [ ... ] } }} - if (!result[item.status]) { - result[item.status] = {}; - } + result[item.status] ||= {}; const key = item.expected ? 'expected' : 'unexpected'; - if (!result[item.status][key]) { - result[item.status][key] = []; - } + result[item.status][key] ||= []; const hasName = result[item.status][key].includes(item.name); if (!hasName) { result[item.status][key].push(item.name); diff --git a/test/parallel/test-http-abort-queued.js b/test/parallel/test-http-abort-queued.js index 17950c106c3769..98359cbce22874 100644 --- a/test/parallel/test-http-abort-queued.js +++ b/test/parallel/test-http-abort-queued.js @@ -34,7 +34,7 @@ const server = http.createServer(common.mustCall((req, res) => { res.writeHead(200); res.write('foo'); - complete = complete || function() { + complete ??= function() { res.end(); }; })); diff --git a/test/parallel/test-http-host-header-ipv6-fail.js b/test/parallel/test-http-host-header-ipv6-fail.js index e84e9ab05b2196..74c61c534f4237 100644 --- a/test/parallel/test-http-host-header-ipv6-fail.js +++ b/test/parallel/test-http-host-header-ipv6-fail.js @@ -26,7 +26,7 @@ function createLocalConnection(options) { } http.createServer(common.mustCall(function(req, res) { - this.requests = this.requests || 0; + this.requests ||= 0; assert.strictEqual(req.headers.host, req.headers.expectedhost); res.end(); if (++this.requests === requests.length) diff --git a/test/parallel/test-http-parser.js b/test/parallel/test-http-parser.js index 739beaa3d67cd9..ad591319089c1a 100644 --- a/test/parallel/test-http-parser.js +++ b/test/parallel/test-http-parser.js @@ -256,7 +256,7 @@ function expectBody(expected) { assert.strictEqual(versionMajor, 1); assert.strictEqual(versionMinor, 0); - headers = headers || parser.headers; + headers ||= parser.headers; assert.strictEqual(headers.length, 2 * 256); // 256 key/value pairs for (let i = 0; i < headers.length; i += 2) { diff --git a/test/parallel/test-http2-create-client-secure-session.js b/test/parallel/test-http2-create-client-secure-session.js index 2f7678cc689825..27014874621707 100644 --- a/test/parallel/test-http2-create-client-secure-session.js +++ b/test/parallel/test-http2-create-client-secure-session.js @@ -40,7 +40,7 @@ function verifySecureSession(key, cert, ca, opts) { server.on('stream', common.mustCall(onStream)); server.on('close', common.mustCall()); server.listen(0, common.mustCall(() => { - opts = opts || { }; + opts ||= {}; opts.secureContext = tls.createSecureContext({ ca }); const client = h2.connect(`https://localhost:${server.address().port}`, opts); diff --git a/test/parallel/test-perf-hooks-resourcetiming.js b/test/parallel/test-perf-hooks-resourcetiming.js index 67893ca9741967..f76cd669004ebc 100644 --- a/test/parallel/test-perf-hooks-resourcetiming.js +++ b/test/parallel/test-perf-hooks-resourcetiming.js @@ -36,18 +36,12 @@ function createTimingInfo({ finalConnectionTimingInfo = null }) { if (finalConnectionTimingInfo !== null) { - finalConnectionTimingInfo.domainLookupStartTime = - finalConnectionTimingInfo.domainLookupStartTime || 0; - finalConnectionTimingInfo.domainLookupEndTime = - finalConnectionTimingInfo.domainLookupEndTime || 0; - finalConnectionTimingInfo.connectionStartTime = - finalConnectionTimingInfo.connectionStartTime || 0; - finalConnectionTimingInfo.connectionEndTime = - finalConnectionTimingInfo.connectionEndTime || 0; - finalConnectionTimingInfo.secureConnectionStartTime = - finalConnectionTimingInfo.secureConnectionStartTime || 0; - finalConnectionTimingInfo.ALPNNegotiatedProtocol = - finalConnectionTimingInfo.ALPNNegotiatedProtocol || []; + finalConnectionTimingInfo.domainLookupStartTime ||= 0; + finalConnectionTimingInfo.domainLookupEndTime ||= 0; + finalConnectionTimingInfo.connectionStartTime ||= 0; + finalConnectionTimingInfo.connectionEndTime ||= 0; + finalConnectionTimingInfo.secureConnectionStartTime ||= 0; + finalConnectionTimingInfo.ALPNNegotiatedProtocol ||= []; } return { startTime, diff --git a/test/parallel/test-stream-big-packet.js b/test/parallel/test-stream-big-packet.js index fdbe3cd21145ee..daa486c0a7b312 100644 --- a/test/parallel/test-stream-big-packet.js +++ b/test/parallel/test-stream-big-packet.js @@ -28,10 +28,8 @@ let passed = false; class TestStream extends stream.Transform { _transform(chunk, encoding, done) { - if (!passed) { - // Char 'a' only exists in the last write - passed = chunk.toString().includes('a'); - } + // Char 'a' only exists in the last write + passed ||= chunk.toString().includes('a'); done(); } } diff --git a/test/parallel/test-stream2-transform.js b/test/parallel/test-stream2-transform.js index 2636484ef4509f..f222f1c03b48b5 100644 --- a/test/parallel/test-stream2-transform.js +++ b/test/parallel/test-stream2-transform.js @@ -213,9 +213,7 @@ const { PassThrough, Transform } = require('stream'); pt.state = ''; pt._transform = function(chunk, encoding, cb) { - if (!chunk) - chunk = ''; - const s = chunk.toString(); + const s = (chunk ||= '').toString(); setTimeout(() => { this.state += s.charAt(0); if (this.state.length === 3) { diff --git a/test/parallel/test-tls-client-verify.js b/test/parallel/test-tls-client-verify.js index a8de1078bf2e9a..54712794331192 100644 --- a/test/parallel/test-tls-client-verify.js +++ b/test/parallel/test-tls-client-verify.js @@ -73,13 +73,9 @@ function testServers(index, servers, clientOptions, cb) { const ok = serverOptions.ok; - if (serverOptions.key) { - serverOptions.key = loadPEM(serverOptions.key); - } + serverOptions.key &&= loadPEM(serverOptions.key); - if (serverOptions.cert) { - serverOptions.cert = loadPEM(serverOptions.cert); - } + serverOptions.cert &&= loadPEM(serverOptions.cert); const server = tls.createServer(serverOptions, common.mustCall(function(s) { s.end('hello world\n'); diff --git a/test/parallel/test-tls-ticket.js b/test/parallel/test-tls-ticket.js index 8d9cd8cdd25155..dd781cb6410b58 100644 --- a/test/parallel/test-tls-ticket.js +++ b/test/parallel/test-tls-ticket.js @@ -135,7 +135,7 @@ function start(callback) { connect(); }); s.on('session', (session) => { - sess = sess || session; + sess ||= session; }); s.once('session', (session) => onNewSession(s, session)); s.once('session', () => ticketLog.push(s.getTLSTicket().toString('hex'))); diff --git a/test/parallel/test-vm-cached-data.js b/test/parallel/test-vm-cached-data.js index a9f1293647278e..39ae3fcdacd054 100644 --- a/test/parallel/test-vm-cached-data.js +++ b/test/parallel/test-vm-cached-data.js @@ -9,8 +9,7 @@ function getSource(tag) { } function produce(source, count) { - if (!count) - count = 1; + count ||= 1; const out = spawnSync(process.execPath, [ '-e', ` 'use strict'; diff --git a/test/parallel/test-zlib-random-byte-pipes.js b/test/parallel/test-zlib-random-byte-pipes.js index d8d039a6d65c4f..918f0df629280d 100644 --- a/test/parallel/test-zlib-random-byte-pipes.js +++ b/test/parallel/test-zlib-random-byte-pipes.js @@ -41,17 +41,17 @@ class RandomReadStream extends Stream { this._processing = false; this._hasher = crypto.createHash('sha1'); - opt = opt || {}; + opt ||= {}; // base block size. - opt.block = opt.block || 256 * 1024; + opt.block ||= 256 * 1024; // Total number of bytes to emit - opt.total = opt.total || 256 * 1024 * 1024; + opt.total ||= 256 * 1024 * 1024; this._remaining = opt.total; // How variable to make the block sizes - opt.jitter = opt.jitter || 1024; + opt.jitter ||= 1024; this._opt = opt; diff --git a/tools/doc/common.mjs b/tools/doc/common.mjs index 2f838e3b15016a..a5dcc04c681947 100644 --- a/tools/doc/common.mjs +++ b/tools/doc/common.mjs @@ -20,26 +20,18 @@ export function extractAndParseYAML(text) { // js-yaml.load() throws on error. const meta = yaml.load(text); - if (meta.added) { - // Since semver-minors can trickle down to previous major versions, - // features may have been added in multiple versions. - meta.added = arrify(meta.added); - } - - if (meta.napiVersion) { - meta.napiVersion = arrify(meta.napiVersion); - } - - if (meta.deprecated) { - // Treat deprecated like added for consistency. - meta.deprecated = arrify(meta.deprecated); - } - - if (meta.removed) { - meta.removed = arrify(meta.removed); - } - - meta.changes = meta.changes || []; + // Since semver-minors can trickle down to previous major versions, + // features may have been added in multiple versions. + meta.added &&= arrify(meta.added); + + meta.napiVersion &&= arrify(meta.napiVersion); + + // Treat deprecated like added for consistency. + meta.deprecated &&= arrify(meta.deprecated); + + meta.removed &&= arrify(meta.removed); + + meta.changes ||= []; return meta; } diff --git a/tools/doc/generate.mjs b/tools/doc/generate.mjs index e15b91159217a0..17beb353083833 100644 --- a/tools/doc/generate.mjs +++ b/tools/doc/generate.mjs @@ -72,7 +72,7 @@ async function main() { } } - nodeVersion = nodeVersion || process.version; + nodeVersion ||= process.version; if (!filename) { throw new Error('No input file specified'); diff --git a/tools/doc/html.mjs b/tools/doc/html.mjs index e0e7706821908f..68762d89e048ce 100644 --- a/tools/doc/html.mjs +++ b/tools/doc/html.mjs @@ -428,8 +428,8 @@ export function buildToc({ filename, apilinks }) { const isDeprecationHeading = DEPRECATION_HEADING_PATTERN.test(headingText); if (isDeprecationHeading) { - if (!node.data) node.data = {}; - if (!node.data.hProperties) node.data.hProperties = {}; + node.data ||= {}; + node.data.hProperties ||= {}; node.data.hProperties.id = headingText.substring(0, headingText.indexOf(':')); } diff --git a/tools/doc/json.mjs b/tools/doc/json.mjs index 509173ca3864a2..647019e24d8eba 100644 --- a/tools/doc/json.mjs +++ b/tools/doc/json.mjs @@ -220,10 +220,10 @@ export function jsonAPI({ filename }) { // which are actually just descriptions of a constructor class signature. // Merge them into the parent. if (current.type === 'class' && current.ctors) { - current.signatures = current.signatures || []; + current.signatures ||= []; const sigs = current.signatures; current.ctors.forEach((ctor) => { - ctor.signatures = ctor.signatures || [{}]; + ctor.signatures ||= [{}]; ctor.signatures.forEach((sig) => { sig.desc = ctor.desc; }); @@ -261,8 +261,8 @@ export function jsonAPI({ filename }) { } if (parent[key] && Array.isArray(parent[key])) { parent[key] = parent[key].concat(current[key]); - } else if (!parent[key]) { - parent[key] = current[key]; + } else { + parent[key] ||= current[key]; } } }); @@ -271,7 +271,7 @@ export function jsonAPI({ filename }) { // Add this section to the parent. Sometimes we have two headings with a // single blob of description. If the preceding entry at this level // shares a name and is lacking a description, copy it backwards. - if (!parent[plur]) parent[plur] = []; + parent[plur] ||= []; const prev = parent[plur].slice(-1)[0]; if (prev && prev.name === current.name && !prev.desc) { prev.desc = current.desc; diff --git a/tools/doc/markdown.mjs b/tools/doc/markdown.mjs index f039391a52730a..6a334585246adc 100644 --- a/tools/doc/markdown.mjs +++ b/tools/doc/markdown.mjs @@ -7,12 +7,10 @@ export function replaceLinks({ filename, linksMapper }) { const fileHtmlUrls = linksMapper[filename]; visit(tree, (node) => { - if (node.url) { - node.url = node.url.replace( - referenceToLocalMdFile, - (_, filename, hash) => `${filename}.html${hash || ''}`, - ); - } + node.url &&= node.url.replace( + referenceToLocalMdFile, + (_, filename, hash) => `${filename}.html${hash || ''}`, + ); }); visit(tree, 'definition', (node) => { const htmlUrl = fileHtmlUrls?.[node.identifier]; diff --git a/tools/eslint-rules/no-unescaped-regexp-dot.js b/tools/eslint-rules/no-unescaped-regexp-dot.js index 6aa6d25bf20f11..7cc714edfa4bca 100644 --- a/tools/eslint-rules/no-unescaped-regexp-dot.js +++ b/tools/eslint-rules/no-unescaped-regexp-dot.js @@ -42,8 +42,7 @@ module.exports = { break; case ']': if (!escaping) { - if (inCharClass) - inCharClass = false; + inCharClass &&= false; } else { escaping = false; } @@ -63,8 +62,7 @@ module.exports = { } break; default: - if (escaping) - escaping = false; + escaping &&= false; } } } diff --git a/tools/license2rtf.mjs b/tools/license2rtf.mjs index 47a55d0d3dd9bd..4d7327e5017640 100644 --- a/tools/license2rtf.mjs +++ b/tools/license2rtf.mjs @@ -93,8 +93,7 @@ class ParagraphParser extends Stream { // Strip comments around block if (this.blockIsLicenseBlock) { - if (!this.blockHasCStyleComment) - this.blockHasCStyleComment = /^\s*(\/\*)/.test(line); + this.blockHasCStyleComment ||= /^\s*(\/\*)/.test(line); if (this.blockHasCStyleComment) { const prev = line; line = line.replace(/^(\s*?)(?:\s?\*\/|\/\*\s|\s\*\s?)/, '$1'); diff --git a/tools/lint-sh.mjs b/tools/lint-sh.mjs index 3c6815815ebcf1..b6fc1c02f1897f 100755 --- a/tools/lint-sh.mjs +++ b/tools/lint-sh.mjs @@ -72,7 +72,7 @@ async function checkFiles(...files) { await fd.truncate(toWrite.length); await fd.write(toWrite, 0, toWrite.length, 0); } else { - if (!process.exitCode) process.exitCode = 1; + process.exitCode ||= 1; console.error( (process.env.GITHUB_ACTIONS ? `::error file=${file},line=1,col=1::` :