From a46a3737a8dc8373b11ca4d57dc42316bdb05d2d Mon Sep 17 00:00:00 2001 From: RedYetiDev <38299977+RedYetiDev@users.noreply.github.com> Date: Sun, 22 Sep 2024 16:16:54 -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 | 6 ++-- lib/_tls_wrap.js | 2 +- lib/assert.js | 2 +- lib/async_hooks.js | 3 +- 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 | 9 ++---- lib/internal/fs/promises.js | 2 +- lib/internal/fs/sync_write_stream.js | 4 +-- 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/options.js | 18 +++-------- lib/internal/process/per_thread.js | 7 ++-- lib/internal/process/warning.js | 4 +-- lib/internal/readline/interface.js | 3 +- lib/internal/source_map/source_map_cache.js | 4 +-- lib/internal/streams/duplex.js | 8 ++--- lib/internal/streams/pipeline.js | 10 ++---- 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 | 4 +-- lib/repl.js | 22 ++++++------- lib/timers.js | 8 ++--- lib/url.js | 14 ++++---- test/async-hooks/init-hooks.js | 2 +- test/async-hooks/verify-graph.js | 6 ++-- test/common/shared-lib-util.js | 4 +-- 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 | 4 +-- ...test-http2-create-client-secure-session.js | 3 +- .../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 | 9 +++--- 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 +- 74 files changed, 181 insertions(+), 333 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 67d21b540f945a..e9b03f89c6aa5f 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 1f7989b843c073..400fc818db6709 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 6d3b3591e7ba40..c94902648aff5e 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 200e7a731daf08..5ac01d3493b0fd 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 && 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..de2d90d5297a69 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; @@ -93,9 +93,7 @@ function SecureContext(secureProtocol, secureOptions, minVersion, maxVersion) { } } -function createSecureContext(options) { - if (!options) options = kEmptyObject; - +function createSecureContext(options = kEmptyObject) { const { honorCipherOrder, minVersion, diff --git a/lib/_tls_wrap.js b/lib/_tls_wrap.js index 2273b3c91b62b4..cca88b1c2c195c 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 9e54983c8682a3..92f7ddd0b1044e 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..3f79d036e5e059 100644 --- a/lib/async_hooks.js +++ b/lib/async_hooks.js @@ -268,8 +268,7 @@ class AsyncResource { return bound; } - static bind(fn, type, thisArg) { - type = type || fn.name; + static bind(fn, type = fn.name, thisArg) { return (new AsyncResource(type || 'bound-anonymous-fn')).bind(fn, thisArg); } } diff --git a/lib/child_process.js b/lib/child_process.js index 580a441a803bdd..28342ebdcd1325 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'); @@ -417,13 +413,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 5f93526e301f43..05daa70b134c02 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 cb20ddd6b85476..48c6bc4664cc24 100644 --- a/lib/events.js +++ b/lib/events.js @@ -338,7 +338,7 @@ EventEmitter.init = function(opts) { this[kShapeMode] = true; } - this._maxListeners = this._maxListeners || undefined; + this._maxListeners ||= undefined; if (opts?.captureRejections) { @@ -458,7 +458,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 c694a8f26fe425..6a8354fd522fc5 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 && 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 501fd6d739ad19..c9b1b8a7a9b06f 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 ee1d09581696d3..de7fb7c673ffe2 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 89f24eab9b1989..df3f7399a9242a 100644 --- a/lib/internal/error_serdes.js +++ b/lib/internal/error_serdes.js @@ -103,15 +103,12 @@ function GetName(object) { let internalUtilInspect; function inspect(...args) { - if (!internalUtilInspect) { - internalUtilInspect = require('internal/util/inspect'); - } - return internalUtilInspect.inspect(...args); + return (internalUtilInspect ??= require('internal/util/inspect')).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 +154,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..5d4bfcef3b8a50 100644 --- a/lib/internal/fs/sync_write_stream.js +++ b/lib/internal/fs/sync_write_stream.js @@ -9,11 +9,9 @@ const { kEmptyObject } = require('internal/util'); const { Writable } = require('stream'); const { closeSync, writeSync } = require('fs'); -function SyncWriteStream(fd, options) { +function SyncWriteStream(fd, options = kEmptyObject) { ReflectApply(Writable, this, [{ autoDestroy: true }]); - options = options || kEmptyObject; - this.fd = fd; this.readable = false; this.autoClose = options.autoClose === undefined ? true : options.autoClose; 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 e5cd20ed0369c4..809650798a8421 100644 --- a/lib/internal/modules/helpers.js +++ b/lib/internal/modules/helpers.js @@ -117,8 +117,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/options.js b/lib/internal/options.js index 68acdb2a7b378e..1192b46c9ede82 100644 --- a/lib/internal/options.js +++ b/lib/internal/options.js @@ -17,24 +17,15 @@ let embedderOptions; // complete so that we don't accidentally include runtime-dependent // states into a runtime-independent snapshot. function getCLIOptionsFromBinding() { - if (!optionsDict) { - optionsDict = getCLIOptionsValues(); - } - return optionsDict; + return optionsDict ??= getCLIOptionsValues(); } function getCLIOptionsInfoFromBinding() { - if (!cliInfo) { - cliInfo = getCLIOptionsInfo(); - } - return cliInfo; + return cliInfo ??= getCLIOptionsInfo(); } function getEmbedderOptions() { - if (!embedderOptions) { - embedderOptions = getEmbedderOptionsFromBinding(); - } - return embedderOptions; + return embedderOptions ??= getEmbedderOptionsFromBinding(); } function refreshOptions() { @@ -42,8 +33,7 @@ function refreshOptions() { } function getOptionValue(optionName) { - const optionsDict = getCLIOptionsFromBinding(); - return optionsDict[optionName]; + return getCLIOptionsFromBinding()[optionName]; } function getAllowUnauthorized() { diff --git a/lib/internal/process/per_thread.js b/lib/internal/process/per_thread.js index 70dcca3e8f0d96..5092cb293d9f85 100644 --- a/lib/internal/process/per_thread.js +++ b/lib/internal/process/per_thread.js @@ -212,7 +212,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 { @@ -414,10 +414,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 162d0ca8153d1c..93b2792f311143 100644 --- a/lib/internal/process/warning.js +++ b/lib/internal/process/warning.js @@ -59,9 +59,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 7c1a15f3c70012..1a84eaab1428dc 100644 --- a/lib/internal/readline/interface.js +++ b/lib/internal/readline/interface.js @@ -1052,9 +1052,8 @@ class Interface extends InterfaceConstructor { } // Handle a write from the tty - [kTtyWrite](s, key) { + [kTtyWrite](s, key = kEmptyObject) { const previousKey = this[kPreviousKey]; - key = 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 9defc32da8e1e6..75e8539f61583b 100644 --- a/lib/internal/source_map/source_map_cache.js +++ b/lib/internal/source_map/source_map_cache.js @@ -340,9 +340,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..5f330f6aca3ab4 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,5 @@ Duplex.toWeb = function(duplex) { let duplexify; Duplex.from = function(body) { - if (!duplexify) { - duplexify = require('internal/streams/duplexify'); - } - return duplexify(body, 'body'); + return (duplexify ??= require('internal/streams/duplexify'))(body, 'body'); }; diff --git a/lib/internal/streams/pipeline.js b/lib/internal/streams/pipeline.js index c3cc742a0de14a..737f8f7dcf287f 100644 --- a/lib/internal/streams/pipeline.js +++ b/lib/internal/streams/pipeline.js @@ -87,11 +87,7 @@ function makeAsyncIterable(val) { } async function* fromReadable(val) { - if (!Readable) { - Readable = require('internal/streams/readable'); - } - - yield* Readable.prototype[SymbolAsyncIterator].call(val); + yield* (Readable ??= require('internal/streams/readable')).prototype[SymbolAsyncIterator].call(val); } async function pumpToNode(iterable, writable, finish, { end }) { @@ -319,9 +315,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 17f8e53ad56339..3c798174dd304b 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 7ef57020728302..d905a08a13161b 100644 --- a/lib/internal/test_runner/coverage.js +++ b/lib/internal/test_runner/coverage.js @@ -481,14 +481,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); - } + // 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 dc77fc429935b6..281b9467de6db8 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 ab2c9278a83739..01e0e6221e3fe3 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 && 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 4591e3b977cc51..283e8891bd2b23 100644 --- a/lib/net.js +++ b/lib/net.js @@ -1046,10 +1046,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)', @@ -1446,9 +1446,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 abc5b25d2e00e6..c06d891ffef2e0 100644 --- a/lib/readline.js +++ b/lib/readline.js @@ -464,9 +464,7 @@ Interface.prototype._getCursorPos = _Interface.prototype.getCursorPos; Interface.prototype._moveCursor = _Interface.prototype[kMoveCursor]; Interface.prototype._ttyWrite = _Interface.prototype[kTtyWrite]; -function _ttyWriteDumb(s, key) { - key = key || kEmptyObject; - +function _ttyWriteDumb(s, key = kEmptyObject) { if (key.name === 'escape') return; if (this[kSawReturnAt] && key.name !== 'enter') diff --git a/lib/repl.js b/lib/repl.js index 88e2dc37d6f9d7..5886fbb94d8b0e 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) { @@ -1006,8 +1005,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 || {}; + self._ttyWrite = (d, key = {}) => { if (paused && !(self.breakEvalOnSigint && key.ctrl && key.name === 'c')) { ArrayPrototypePush(pausedBuffer, ['key', [d, key], self.isCompletionEnabled]); @@ -1553,9 +1551,7 @@ function complete(line, callback) { ArrayPrototypeMap(group, (member) => `${expr}${member}`)); }); - if (filter) { - filter = `${expr}${filter}`; - } + filter &&= `${expr}${filter}`; } completionGroupsLoaded(); @@ -1645,8 +1641,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 b594f79d120e40..1f1b9ebc35621f 100644 --- a/lib/timers.js +++ b/lib/timers.js @@ -170,9 +170,7 @@ ObjectDefineProperty(setTimeout, customPromisify, { __proto__: null, enumerable: true, get() { - if (!timersPromises) - timersPromises = require('timers/promises'); - return timersPromises.setTimeout; + return (timersPromises ??= require('timers/promises')).setTimeout; }, }); @@ -309,9 +307,7 @@ ObjectDefineProperty(setImmediate, customPromisify, { __proto__: null, enumerable: true, get() { - if (!timersPromises) - timersPromises = require('timers/promises'); - return timersPromises.setImmediate; + return (timersPromises ??= require('timers/promises')).setImmediate; }, }); diff --git a/lib/url.js b/lib/url.js index 8fa8553c2b3f30..a08eb9048f734a 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 2c5167156b615d..8410e328352563 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..71f366a62e3af1 100644 --- a/test/common/shared-lib-util.js +++ b/test/common/shared-lib-util.js @@ -8,13 +8,11 @@ const kExecPath = path.dirname(process.execPath); // If node executable is linked to shared lib, need to take care about the // shared lib path. -function addLibraryPath(env) { +function addLibraryPath(env = process.env) { if (!kNodeShared) { return; } - env = env || process.env; - env.LD_LIBRARY_PATH = (env.LD_LIBRARY_PATH ? env.LD_LIBRARY_PATH + path.delimiter : '') + kExecPath; 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..41aa33ce3ec628 100644 --- a/test/parallel/test-http-parser.js +++ b/test/parallel/test-http-parser.js @@ -249,15 +249,13 @@ function expectBody(expected) { '\r\n' ); - const onHeadersComplete = (versionMajor, versionMinor, headers, + const onHeadersComplete = (versionMajor, versionMinor, headers = parser.headers, method, url) => { assert.strictEqual(method, methods.indexOf('GET')); assert.strictEqual(url || parser.url, '/foo/bar/baz?quux=42#1337'); assert.strictEqual(versionMajor, 1); assert.strictEqual(versionMinor, 0); - headers = headers || parser.headers; - assert.strictEqual(headers.length, 2 * 256); // 256 key/value pairs for (let i = 0; i < headers.length; i += 2) { assert.strictEqual(headers[i], 'X-Filler'); diff --git a/test/parallel/test-http2-create-client-secure-session.js b/test/parallel/test-http2-create-client-secure-session.js index 2f7678cc689825..7fedcb94d39c94 100644 --- a/test/parallel/test-http2-create-client-secure-session.js +++ b/test/parallel/test-http2-create-client-secure-session.js @@ -35,12 +35,11 @@ function onStream(stream, headers) { })); } -function verifySecureSession(key, cert, ca, opts) { +function verifySecureSession(key, cert, ca, opts = {}) { const server = h2.createSecureServer({ cert, key }); server.on('stream', common.mustCall(onStream)); server.on('close', common.mustCall()); server.listen(0, common.mustCall(() => { - 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..27979ae265e550 100644 --- a/test/parallel/test-zlib-random-byte-pipes.js +++ b/test/parallel/test-zlib-random-byte-pipes.js @@ -33,7 +33,7 @@ const Stream = stream.Stream; // Emit random bytes, and keep a shasum class RandomReadStream extends Stream { - constructor(opt) { + constructor(opt = {}) { super(); this.readable = true; @@ -41,17 +41,16 @@ class RandomReadStream extends Stream { this._processing = false; this._hasher = crypto.createHash('sha1'); - 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 21104e592b8a24..bab1397e6c1c49 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 && fileHtmlUrls[node.identifier]; diff --git a/tools/eslint-rules/no-unescaped-regexp-dot.js b/tools/eslint-rules/no-unescaped-regexp-dot.js index 6db23732c81fd5..a49834832ba3f0 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::` :