lib: prefer logical assignment

PR-URL: https://github.com/nodejs/node/pull/55044
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Chemi Atlow <chemi@atlow.co.il>
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
Reviewed-By: LiviaMedeiros <livia@cirno.name>
This commit is contained in:
Aviv Keller 2024-10-09 02:42:16 -04:00 committed by GitHub
parent 09d10b50dc
commit 71785889c8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
73 changed files with 172 additions and 296 deletions

View File

@ -110,7 +110,7 @@ class TestDoubleBenchmarker {
} }
create(options) { create(options) {
process.env.duration = process.env.duration || options.duration || 5; process.env.duration ||= options.duration || 5;
const scheme = options.scheme || 'http'; const scheme = options.scheme || 'http';
const env = { const env = {

View File

@ -113,8 +113,7 @@ class Benchmark {
} }
const [, key, value] = match; const [, key, value] = match;
if (configs[key] !== undefined) { if (configs[key] !== undefined) {
if (!cliOptions[key]) cliOptions[key] ||= [];
cliOptions[key] = [];
cliOptions[key].push( cliOptions[key].push(
// Infer the type from the config object and parse accordingly // Infer the type from the config object and parse accordingly
typeof configs[key][0] === 'number' ? +value : value, typeof configs[key][0] === 'number' ? +value : value,
@ -177,10 +176,9 @@ class Benchmark {
http(options, cb) { http(options, cb) {
const http_options = { ...options }; const http_options = { ...options };
http_options.benchmarker = http_options.benchmarker || http_options.benchmarker ||= this.config.benchmarker ||
this.config.benchmarker || this.extra_options.benchmarker ||
this.extra_options.benchmarker || http_benchmarkers.default_http_benchmarker;
http_benchmarkers.default_http_benchmarker;
http_benchmarkers.run( http_benchmarkers.run(
http_options, (error, code, used_benchmarker, result, elapsed) => { http_options, (error, code, used_benchmarker, result, elapsed) => {
if (cb) { if (cb) {

View File

@ -9,8 +9,8 @@ const bench = common.createBenchmark(main, {
}); });
function oldStyleDefaults(x, y) { function oldStyleDefaults(x, y) {
x = x || 1; x ||= 1;
y = y || 2; y ||= 2;
assert.strictEqual(x, 1); assert.strictEqual(x, 1);
assert.strictEqual(y, 2); assert.strictEqual(y, 2);
} }

View File

@ -21,18 +21,12 @@ function createTimingInfo({
finalConnectionTimingInfo = null, finalConnectionTimingInfo = null,
}) { }) {
if (finalConnectionTimingInfo !== null) { if (finalConnectionTimingInfo !== null) {
finalConnectionTimingInfo.domainLookupStartTime = finalConnectionTimingInfo.domainLookupStartTime ||= 0;
finalConnectionTimingInfo.domainLookupStartTime || 0; finalConnectionTimingInfo.domainLookupEndTime ||= 0;
finalConnectionTimingInfo.domainLookupEndTime = finalConnectionTimingInfo.connectionStartTime ||= 0;
finalConnectionTimingInfo.domainLookupEndTime || 0; finalConnectionTimingInfo.connectionEndTime ||= 0;
finalConnectionTimingInfo.connectionStartTime = finalConnectionTimingInfo.secureConnectionStartTime ||= 0;
finalConnectionTimingInfo.connectionStartTime || 0; finalConnectionTimingInfo.ALPNNegotiatedProtocol ||= [];
finalConnectionTimingInfo.connectionEndTime =
finalConnectionTimingInfo.connectionEndTime || 0;
finalConnectionTimingInfo.secureConnectionStartTime =
finalConnectionTimingInfo.secureConnectionStartTime || 0;
finalConnectionTimingInfo.ALPNNegotiatedProtocol =
finalConnectionTimingInfo.ALPNNegotiatedProtocol || [];
} }
return { return {
startTime, startTime,

View File

@ -10,7 +10,7 @@ const bench = common.createBenchmark(main, {
function main({ n, method, inputLen }) { function main({ n, method, inputLen }) {
// Default method value for testing. // Default method value for testing.
method = method || 'deflate'; method ||= 'deflate';
const chunk = Buffer.alloc(inputLen, 'a'); const chunk = Buffer.alloc(inputLen, 'a');
switch (method) { switch (method) {

View File

@ -10,7 +10,7 @@ const bench = common.createBenchmark(main, {
function main({ n, method, inputLen }) { function main({ n, method, inputLen }) {
// Default method value for tests. // Default method value for tests.
method = method || 'inflate'; method ||= 'inflate';
const chunk = zlib.deflateSync(Buffer.alloc(inputLen, 'a')); const chunk = zlib.deflateSync(Buffer.alloc(inputLen, 'a'));
let i = 0; let i = 0;

View File

@ -144,6 +144,7 @@ export default [
ignorePattern: '.*', ignorePattern: '.*',
}, },
}], }],
'logical-assignment-operators': ['error', 'always', { enforceForIfStatements: true }],
'default-case-last': 'error', 'default-case-last': 'error',
'dot-notation': 'error', 'dot-notation': 'error',
'eqeqeq': ['error', 'smart'], 'eqeqeq': ['error', 'smart'],

View File

@ -246,9 +246,7 @@ Agent.prototype.addRequest = function addRequest(req, options, port/* legacy */,
normalizeServerName(options, req); normalizeServerName(options, req);
const name = this.getName(options); const name = this.getName(options);
if (!this.sockets[name]) { this.sockets[name] ||= [];
this.sockets[name] = [];
}
const freeSockets = this.freeSockets[name]; const freeSockets = this.freeSockets[name];
let socket; let socket;
@ -284,9 +282,7 @@ Agent.prototype.addRequest = function addRequest(req, options, port/* legacy */,
} else { } else {
debug('wait for socket'); debug('wait for socket');
// We are over limit so we'll add it to the queue. // 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 // Used to create sockets for pending requests from different origin
req[kRequestOptions] = options; req[kRequestOptions] = options;
@ -313,9 +309,7 @@ Agent.prototype.createSocket = function createSocket(req, options, cb) {
const oncreate = once((err, s) => { const oncreate = once((err, s) => {
if (err) if (err)
return cb(err); return cb(err);
if (!this.sockets[name]) { this.sockets[name] ||= [];
this.sockets[name] = [];
}
this.sockets[name].push(s); this.sockets[name].push(s);
this.totalSocketCount++; this.totalSocketCount++;
debug('sockets', name, this.sockets[name].length, this.totalSocketCount); debug('sockets', name, this.sockets[name].length, this.totalSocketCount);

View File

@ -347,8 +347,8 @@ function ClientRequest(input, options, cb) {
opts = { ...optsWithoutSignal }; opts = { ...optsWithoutSignal };
if (opts.socketPath) { if (opts.socketPath) {
opts.path = opts.socketPath; opts.path = opts.socketPath;
} else if (opts.path) { } else {
opts.path = undefined; opts.path &&= undefined;
} }
} }
if (typeof opts.createConnection === 'function') { if (typeof opts.createConnection === 'function') {

View File

@ -357,8 +357,7 @@ function writeHead(statusCode, reason, obj) {
this.statusMessage = reason; this.statusMessage = reason;
} else { } else {
// writeHead(statusCode[, headers]) // writeHead(statusCode[, headers])
if (!this.statusMessage) this.statusMessage ||= STATUS_CODES[statusCode] || 'unknown';
this.statusMessage = STATUS_CODES[statusCode] || 'unknown';
obj ??= reason; obj ??= reason;
} }
this.statusCode = statusCode; this.statusCode = statusCode;
@ -510,9 +509,7 @@ function storeHTTPOptions(options) {
function setupConnectionsTracking() { function setupConnectionsTracking() {
// Start connection handling // Start connection handling
if (!this[kConnections]) { this[kConnections] ||= new ConnectionsList();
this[kConnections] = new ConnectionsList();
}
if (this[kConnectionsCheckingInterval]) { if (this[kConnectionsCheckingInterval]) {
clearInterval(this[kConnectionsCheckingInterval]); clearInterval(this[kConnectionsCheckingInterval]);
@ -923,8 +920,7 @@ function onParserExecuteCommon(server, socket, parser, state, ret, d) {
const req = parser.incoming; const req = parser.incoming;
debug('SERVER upgrade or connect', req.method); debug('SERVER upgrade or connect', req.method);
if (!d) d ||= parser.getCurrentBuffer();
d = parser.getCurrentBuffer();
socket.removeListener('data', state.onData); socket.removeListener('data', state.onData);
socket.removeListener('end', state.onEnd); socket.removeListener('end', state.onEnd);
@ -962,7 +958,7 @@ function onParserExecuteCommon(server, socket, parser, state, ret, d) {
} }
function clearIncoming(req) { function clearIncoming(req) {
req = req || this; req ||= this;
const parser = req.socket?.parser; const parser = req.socket?.parser;
// Reset the .incoming property so that the request object can be gc'ed. // Reset the .incoming property so that the request object can be gc'ed.
if (parser && parser.incoming === req) { if (parser && parser.incoming === req) {

View File

@ -57,7 +57,7 @@ const {
} = require('internal/tls/secure-context'); } = require('internal/tls/secure-context');
function toV(which, v, def) { function toV(which, v, def) {
if (v == null) v = def; v ??= def;
if (v === 'TLSv1') return TLS1_VERSION; if (v === 'TLSv1') return TLS1_VERSION;
if (v === 'TLSv1.1') return TLS1_1_VERSION; if (v === 'TLSv1.1') return TLS1_1_VERSION;
if (v === 'TLSv1.2') return TLS1_2_VERSION; if (v === 'TLSv1.2') return TLS1_2_VERSION;
@ -94,8 +94,7 @@ function SecureContext(secureProtocol, secureOptions, minVersion, maxVersion) {
} }
function createSecureContext(options) { function createSecureContext(options) {
if (!options) options = kEmptyObject; options ||= kEmptyObject;
const { const {
honorCipherOrder, honorCipherOrder,
minVersion, minVersion,

View File

@ -1328,7 +1328,7 @@ function Server(options, listener) {
listener = options; listener = options;
options = kEmptyObject; options = kEmptyObject;
} else if (options == null || typeof options === 'object') { } else if (options == null || typeof options === 'object') {
options = options ?? kEmptyObject; options ??= kEmptyObject;
} else { } else {
throw new ERR_INVALID_ARG_TYPE('options', 'Object', options); throw new ERR_INVALID_ARG_TYPE('options', 'Object', options);
} }

View File

@ -750,7 +750,7 @@ function internalMatch(string, regexp, message, fn) {
const generatedMessage = !message; const generatedMessage = !message;
// 'The input was expected to not match the regular expression ' + // '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 ' + 'The "string" argument must be of type string. Received type ' +
`${typeof string} (${inspect(string)})` : `${typeof string} (${inspect(string)})` :
(match ? (match ?

View File

@ -269,7 +269,7 @@ class AsyncResource {
} }
static bind(fn, type, thisArg) { static bind(fn, type, thisArg) {
type = type || fn.name; type ||= fn.name;
return (new AsyncResource(type || 'bound-anonymous-fn')).bind(fn, thisArg); return (new AsyncResource(type || 'bound-anonymous-fn')).bind(fn, thisArg);
} }
} }

View File

@ -138,7 +138,7 @@ function fork(modulePath, args = [], options) {
validateObject(options, 'options'); validateObject(options, 'options');
} }
options = { __proto__: null, ...options, shell: false }; options = { __proto__: null, ...options, shell: false };
options.execPath = options.execPath || process.execPath; options.execPath ||= process.execPath;
validateArgumentNullCheck(options.execPath, 'options.execPath'); validateArgumentNullCheck(options.execPath, 'options.execPath');
// Prepare arguments for fork: // Prepare arguments for fork:
@ -272,9 +272,7 @@ function normalizeExecFileArgs(file, args, options, callback) {
args = null; args = null;
} }
if (args == null) { args ??= [];
args = [];
}
if (typeof options === 'function') { if (typeof options === 'function') {
callback = options; callback = options;
@ -282,9 +280,7 @@ function normalizeExecFileArgs(file, args, options, callback) {
validateObject(options, 'options'); validateObject(options, 'options');
} }
if (options == null) { options ??= kEmptyObject;
options = kEmptyObject;
}
if (callback != null) { if (callback != null) {
validateFunction(callback, 'callback'); validateFunction(callback, 'callback');
@ -415,13 +411,11 @@ function execFile(file, args, options, callback) {
if (args?.length) if (args?.length)
cmd += ` ${ArrayPrototypeJoin(args, ' ')}`; cmd += ` ${ArrayPrototypeJoin(args, ' ')}`;
if (!ex) { ex ||= genericNodeError(`Command failed: ${cmd}\n${stderr}`, {
ex = genericNodeError(`Command failed: ${cmd}\n${stderr}`, { code: code < 0 ? getSystemErrorName(code) : code,
code: code < 0 ? getSystemErrorName(code) : code, killed: child.killed || killed,
killed: child.killed || killed, signal: signal,
signal: signal, });
});
}
ex.cmd = cmd; ex.cmd = cmd;
callback(ex, stdout, stderr); callback(ex, stdout, stderr);

View File

@ -96,8 +96,7 @@ const SEND_BUFFER = false;
// Lazily loaded // Lazily loaded
let _cluster = null; let _cluster = null;
function lazyLoadCluster() { function lazyLoadCluster() {
if (!_cluster) _cluster = require('cluster'); return _cluster ??= require('cluster');
return _cluster;
} }
function Socket(type, listener) { function Socket(type, listener) {

View File

@ -338,7 +338,7 @@ EventEmitter.init = function(opts) {
this[kShapeMode] = true; this[kShapeMode] = true;
} }
this._maxListeners = this._maxListeners || undefined; this._maxListeners ||= undefined;
if (opts?.captureRejections) { if (opts?.captureRejections) {
@ -458,7 +458,7 @@ EventEmitter.prototype.emit = function emit(type, ...args) {
if (events !== undefined) { if (events !== undefined) {
if (doError && events[kErrorMonitor] !== undefined) if (doError && events[kErrorMonitor] !== undefined)
this.emit(kErrorMonitor, ...args); this.emit(kErrorMonitor, ...args);
doError = (doError && events.error === undefined); doError &&= events.error === undefined;
} else if (!doError) } else if (!doError)
return false; return false;

View File

@ -2,10 +2,7 @@
let error; let error;
function lazyError() { function lazyError() {
if (!error) { return error ??= require('internal/errors').codes.ERR_INTERNAL_ASSERTION;
error = require('internal/errors').codes.ERR_INTERNAL_ASSERTION;
}
return error;
} }
function assert(value, message) { function assert(value, message) {

View File

@ -37,8 +37,7 @@ const {
let workerStdio; let workerStdio;
function lazyWorkerStdio() { function lazyWorkerStdio() {
if (!workerStdio) workerStdio = createWorkerStdio(); return workerStdio ??= createWorkerStdio();
return workerStdio;
} }
function getStdout() { return lazyWorkerStdio().stdout; } function getStdout() { return lazyWorkerStdio().stdout; }

View File

@ -853,8 +853,7 @@ function setupChannel(target, channel, serializationMode) {
if (err === 0) { if (err === 0) {
if (handle) { if (handle) {
if (!this._handleQueue) this._handleQueue ||= [];
this._handleQueue = [];
if (obj?.postSend) if (obj?.postSend)
obj.postSend(message, handle, options, callback, target); obj.postSend(message, handle, options, callback, target);
} }
@ -1010,9 +1009,7 @@ function getValidStdio(stdio, sync) {
} }
// Defaults // Defaults
if (stdio == null) { stdio ??= i < 3 ? 'pipe' : 'ignore';
stdio = i < 3 ? 'pipe' : 'ignore';
}
if (stdio === 'ignore') { if (stdio === 'ignore') {
ArrayPrototypePush(acc, { type: 'ignore' }); ArrayPrototypePush(acc, { type: 'ignore' });

View File

@ -167,9 +167,7 @@ function rr(message, { indexesKey, index }, cb) {
let fakeHandle = null; let fakeHandle = null;
function ref() { function ref() {
if (!fakeHandle) { fakeHandle ||= setInterval(noop, TIMEOUT_MAX);
fakeHandle = setInterval(noop, TIMEOUT_MAX);
}
} }
function unref() { function unref() {

View File

@ -301,8 +301,7 @@ function queryServer(worker, message) {
handles.set(key, handle); handles.set(key, handle);
} }
if (!handle.data) handle.data ||= message.data;
handle.data = message.data;
// Set custom server data // Set custom server data
handle.add(worker, (errno, reply, handle) => { handle.add(worker, (errno, reply, handle) => {

View File

@ -201,8 +201,7 @@ ObjectDefineProperties(Console.prototype, {
enumerable: false, enumerable: false,
configurable: true, configurable: true,
get() { get() {
if (!stdout) stdout = object.stdout; return stdout ||= object.stdout;
return stdout;
}, },
set(value) { stdout = value; }, set(value) { stdout = value; },
}, },
@ -211,8 +210,7 @@ ObjectDefineProperties(Console.prototype, {
enumerable: false, enumerable: false,
configurable: true, configurable: true,
get() { get() {
if (!stderr) { stderr = object.stderr; } return stderr ||= object.stderr;
return stderr;
}, },
set(value) { stderr = value; }, set(value) { stderr = value; },
}, },

View File

@ -92,7 +92,7 @@ const privateDecrypt = rsaFunctionFor(_privateDecrypt, RSA_PKCS1_OAEP_PADDING,
function getDecoder(decoder, encoding) { function getDecoder(decoder, encoding) {
const normalizedEncoding = normalizeEncoding(encoding); const normalizedEncoding = normalizeEncoding(encoding);
decoder = decoder || new StringDecoder(encoding); decoder ||= new StringDecoder(encoding);
if (decoder.encoding !== normalizedEncoding) { if (decoder.encoding !== normalizedEncoding) {
if (normalizedEncoding === undefined) { if (normalizedEncoding === undefined) {
throw new ERR_UNKNOWN_ENCODING(encoding); throw new ERR_UNKNOWN_ENCODING(encoding);
@ -303,8 +303,8 @@ function getCipherInfo(nameOrNid, options) {
const ret = _getCipherInfo({}, nameOrNid, keyLength, ivLength); const ret = _getCipherInfo({}, nameOrNid, keyLength, ivLength);
if (ret !== undefined) { if (ret !== undefined) {
if (ret.name) ret.name = StringPrototypeToLowerCase(ret.name); ret.name &&= StringPrototypeToLowerCase(ret.name);
if (ret.type) ret.type = StringPrototypeToLowerCase(ret.type); ret.type &&= StringPrototypeToLowerCase(ret.type);
} }
return ret; return ret;
} }

View File

@ -242,8 +242,7 @@ const {
} }
get asymmetricKeyType() { get asymmetricKeyType() {
return this[kAsymmetricKeyType] || return this[kAsymmetricKeyType] ||= this[kHandle].getAsymmetricKeyType();
(this[kAsymmetricKeyType] = this[kHandle].getAsymmetricKeyType());
} }
get asymmetricKeyDetails() { get asymmetricKeyDetails() {
@ -252,10 +251,9 @@ const {
case 'rsa-pss': case 'rsa-pss':
case 'dsa': case 'dsa':
case 'ec': case 'ec':
return this[kAsymmetricKeyDetails] || return this[kAsymmetricKeyDetails] ||= normalizeKeyDetails(
(this[kAsymmetricKeyDetails] = normalizeKeyDetails( this[kHandle].keyDetail({}),
this[kHandle].keyDetail({}), );
));
default: default:
return {}; return {};
} }

View File

@ -103,15 +103,13 @@ function GetName(object) {
let internalUtilInspect; let internalUtilInspect;
function inspect(...args) { function inspect(...args) {
if (!internalUtilInspect) { internalUtilInspect ??= require('internal/util/inspect');
internalUtilInspect = require('internal/util/inspect');
}
return internalUtilInspect.inspect(...args); return internalUtilInspect.inspect(...args);
} }
let serialize; let serialize;
function serializeError(error) { function serializeError(error) {
if (!serialize) serialize = require('v8').serialize; serialize ??= require('v8').serialize;
if (typeof error === 'symbol') { if (typeof error === 'symbol') {
return Buffer.from(StringFromCharCode(kInspectedSymbol) + inspect(error), 'utf8'); return Buffer.from(StringFromCharCode(kInspectedSymbol) + inspect(error), 'utf8');
} }
@ -157,7 +155,7 @@ function fromBuffer(error) {
let deserialize; let deserialize;
function deserializeError(error) { function deserializeError(error) {
if (!deserialize) deserialize = require('v8').deserialize; deserialize ??= require('v8').deserialize;
switch (error[0]) { switch (error[0]) {
case kSerializedError: { case kSerializedError: {
const { constructor, properties } = deserialize(error.subarray(1)); const { constructor, properties } = deserialize(error.subarray(1));

View File

@ -1223,7 +1223,7 @@ function isCustomIterable(obj) {
async function appendFile(path, data, options) { async function appendFile(path, data, options) {
options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'a' }); options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'a' });
options = copyObject(options); options = copyObject(options);
options.flag = options.flag || 'a'; options.flag ||= 'a';
return writeFile(path, data, options); return writeFile(path, data, options);
} }

View File

@ -12,7 +12,7 @@ const { closeSync, writeSync } = require('fs');
function SyncWriteStream(fd, options) { function SyncWriteStream(fd, options) {
ReflectApply(Writable, this, [{ autoDestroy: true }]); ReflectApply(Writable, this, [{ autoDestroy: true }]);
options = options || kEmptyObject; options ||= kEmptyObject;
this.fd = fd; this.fd = fd;
this.readable = false; this.readable = false;

View File

@ -147,10 +147,7 @@ const kMaxUserId = 2 ** 32 - 1;
let fs; let fs;
function lazyLoadFs() { function lazyLoadFs() {
if (!fs) { return fs ??= require('fs');
fs = require('fs');
}
return fs;
} }
function assertEncoding(encoding) { function assertEncoding(encoding) {

View File

@ -1279,10 +1279,7 @@ class Http2Session extends EventEmitter {
setupFn(); setupFn();
} }
if (!this[kNativeFields]) { this[kNativeFields] ||= trackAssignmentsTypedArray(new Uint8Array(kSessionUint8FieldCount));
this[kNativeFields] = trackAssignmentsTypedArray(
new Uint8Array(kSessionUint8FieldCount));
}
this.on('newListener', sessionListenerAdded); this.on('newListener', sessionListenerAdded);
this.on('removeListener', sessionListenerRemoved); this.on('removeListener', sessionListenerRemoved);
@ -2448,10 +2445,7 @@ function processHeaders(oldHeaders, options) {
headers[HTTP2_HEADER_STATUS] | 0 || HTTP_STATUS_OK; headers[HTTP2_HEADER_STATUS] | 0 || HTTP_STATUS_OK;
if (options.sendDate == null || options.sendDate) { if (options.sendDate == null || options.sendDate) {
if (headers[HTTP2_HEADER_DATE] === null || headers[HTTP2_HEADER_DATE] ??= utcDate();
headers[HTTP2_HEADER_DATE] === undefined) {
headers[HTTP2_HEADER_DATE] = utcDate();
}
} }
// This is intentionally stricter than the HTTP/1 implementation, which // This is intentionally stricter than the HTTP/1 implementation, which
@ -3123,15 +3117,11 @@ function initializeOptions(options) {
// Used only with allowHTTP1 // Used only with allowHTTP1
options.Http1IncomingMessage = options.Http1IncomingMessage || options.Http1IncomingMessage ||= http.IncomingMessage;
http.IncomingMessage; options.Http1ServerResponse ||= http.ServerResponse;
options.Http1ServerResponse = options.Http1ServerResponse ||
http.ServerResponse;
options.Http2ServerRequest = options.Http2ServerRequest || options.Http2ServerRequest ||= Http2ServerRequest;
Http2ServerRequest; options.Http2ServerResponse ||= Http2ServerResponse;
options.Http2ServerResponse = options.Http2ServerResponse ||
Http2ServerResponse;
return options; return options;
} }
@ -3421,7 +3411,7 @@ function getUnpackedSettings(buf, options = kEmptyObject) {
settings.enableConnectProtocol = value !== 0; settings.enableConnectProtocol = value !== 0;
break; break;
default: default:
if (!settings.customSettings) settings.customSettings = {}; settings.customSettings ||= {};
settings.customSettings[id] = value; settings.customSettings[id] = value;
} }
offset += 4; offset += 4;

View File

@ -86,12 +86,8 @@ function onClientResponseFinish({ request, response }) {
} }
function enable() { function enable() {
if (!dc) { dc ??= require('diagnostics_channel');
dc = require('diagnostics_channel'); Network ??= require('inspector').Network;
}
if (!Network) {
Network = require('inspector').Network;
}
dc.subscribe('http.client.request.start', onClientRequestStart); dc.subscribe('http.client.request.start', onClientRequestStart);
dc.subscribe('http.client.request.error', onClientRequestError); dc.subscribe('http.client.request.error', onClientRequestError);
dc.subscribe('http.client.response.finish', onClientResponseFinish); dc.subscribe('http.client.response.finish', onClientResponseFinish);

View File

@ -118,8 +118,7 @@ let $Module = null;
* Import the Module class on first use. * Import the Module class on first use.
*/ */
function lazyModule() { function lazyModule() {
$Module = $Module || require('internal/modules/cjs/loader').Module; return $Module ??= require('internal/modules/cjs/loader').Module;
return $Module;
} }
/** /**

View File

@ -208,7 +208,7 @@ function wrapProcessMethods(binding) {
// it's monkey-patched by tests. // it's monkey-patched by tests.
err = process._kill(pid, sig); err = process._kill(pid, sig);
} else { } else {
sig = sig || 'SIGTERM'; sig ||= 'SIGTERM';
if (constants[sig]) { if (constants[sig]) {
err = process._kill(pid, constants[sig]); err = process._kill(pid, constants[sig]);
} else { } else {
@ -410,10 +410,7 @@ let traceEventsAsyncHook;
// Dynamically enable/disable the traceEventsAsyncHook // Dynamically enable/disable the traceEventsAsyncHook
function toggleTraceCategoryState(asyncHooksEnabled) { function toggleTraceCategoryState(asyncHooksEnabled) {
if (asyncHooksEnabled) { if (asyncHooksEnabled) {
if (!traceEventsAsyncHook) { traceEventsAsyncHook ||= require('internal/trace_events_async_hooks').createHook();
traceEventsAsyncHook =
require('internal/trace_events_async_hooks').createHook();
}
traceEventsAsyncHook.enable(); traceEventsAsyncHook.enable();
} else if (traceEventsAsyncHook) { } else if (traceEventsAsyncHook) {
traceEventsAsyncHook.disable(); traceEventsAsyncHook.disable();

View File

@ -52,9 +52,7 @@ function lazyOption() {
// so use console.error. // so use console.error.
let error; let error;
function writeOut(message) { function writeOut(message) {
if (!error) { error ??= require('internal/console/global').error;
error = require('internal/console/global').error;
}
error(message); error(message);
} }

View File

@ -1055,7 +1055,7 @@ class Interface extends InterfaceConstructor {
// Handle a write from the tty // Handle a write from the tty
[kTtyWrite](s, key) { [kTtyWrite](s, key) {
const previousKey = this[kPreviousKey]; const previousKey = this[kPreviousKey];
key = key || kEmptyObject; key ||= kEmptyObject;
this[kPreviousKey] = key; this[kPreviousKey] = key;
if (!key.meta || key.name !== 'y') { if (!key.meta || key.name !== 'y') {

View File

@ -338,9 +338,7 @@ function findSourceMap(sourceURL) {
if (RegExpPrototypeExec(kLeadingProtocol, sourceURL) === null) { if (RegExpPrototypeExec(kLeadingProtocol, sourceURL) === null) {
sourceURL = pathToFileURL(sourceURL).href; 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); const entry = getModuleSourceMapCache().get(sourceURL) ?? generatedSourceMapCache.get(sourceURL);
if (entry === undefined) { if (entry === undefined) {
return undefined; return undefined;

View File

@ -54,8 +54,7 @@ ObjectSetPrototypeOf(Duplex, Readable);
// Allow the keys array to be GC'ed. // Allow the keys array to be GC'ed.
for (let i = 0; i < keys.length; i++) { for (let i = 0; i < keys.length; i++) {
const method = keys[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; let duplexify;
Duplex.from = function(body) { Duplex.from = function(body) {
if (!duplexify) { duplexify ??= require('internal/streams/duplexify');
duplexify = require('internal/streams/duplexify');
}
return duplexify(body, 'body'); return duplexify(body, 'body');
}; };

View File

@ -88,10 +88,7 @@ function makeAsyncIterable(val) {
} }
async function* fromReadable(val) { async function* fromReadable(val) {
if (!Readable) { Readable ??= require('internal/streams/readable');
Readable = require('internal/streams/readable');
}
yield* Readable.prototype[SymbolAsyncIterator].call(val); yield* Readable.prototype[SymbolAsyncIterator].call(val);
} }
@ -320,9 +317,7 @@ function pipelineImpl(streams, callback, opts) {
'AsyncIterable', `transform[${i - 1}]`, ret); 'AsyncIterable', `transform[${i - 1}]`, ret);
} }
} else { } else {
if (!PassThrough) { PassThrough ??= require('internal/streams/passthrough');
PassThrough = require('internal/streams/passthrough');
}
// If the last argument to pipeline is not a stream // If the last argument to pipeline is not a stream
// we must create a proxy stream so that pipeline(...) // we must create a proxy stream so that pipeline(...)

View File

@ -410,7 +410,7 @@ function readableAddChunkUnshiftByteMode(stream, state, chunk, encoding) {
} }
if (typeof chunk === 'string') { if (typeof chunk === 'string') {
encoding = encoding || state.defaultEncoding; encoding ||= state.defaultEncoding;
if (state.encoding !== encoding) { if (state.encoding !== encoding) {
if (state.encoding) { if (state.encoding) {
// When unshifting, if state.encoding is set, we have to save // When unshifting, if state.encoding is set, we have to save
@ -466,7 +466,7 @@ function readableAddChunkPushByteMode(stream, state, chunk, encoding) {
} }
if (typeof chunk === 'string') { if (typeof chunk === 'string') {
encoding = encoding || state.defaultEncoding; encoding ||= state.defaultEncoding;
if (state.encoding !== encoding) { if (state.encoding !== encoding) {
chunk = Buffer.from(chunk, encoding); chunk = Buffer.from(chunk, encoding);
encoding = ''; encoding = '';

View File

@ -515,14 +515,12 @@ function sortCoverageFiles(a, b) {
function setupCoverage(options) { function setupCoverage(options) {
let originalCoverageDirectory = process.env.NODE_V8_COVERAGE; let originalCoverageDirectory = process.env.NODE_V8_COVERAGE;
if (originalCoverageDirectory) { // If NODE_V8_COVERAGE was already specified, convert it to an absolute path
// 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
// 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
// so that no preexisting coverage files interfere with the results of the // coverage report. Then, once the coverage is computed, move the coverage
// coverage report. Then, once the coverage is computed, move the coverage // files back to the original NODE_V8_COVERAGE directory.
// files back to the original NODE_V8_COVERAGE directory. originalCoverageDirectory &&= resolve(options.cwd, originalCoverageDirectory);
originalCoverageDirectory = resolve(options.cwd, originalCoverageDirectory);
}
const coverageDirectory = mkdtempSync(join(tmpdir(), 'node-coverage-')); const coverageDirectory = mkdtempSync(join(tmpdir(), 'node-coverage-'));
const enabled = setupCoverageHooks(coverageDirectory); const enabled = setupCoverageHooks(coverageDirectory);

View File

@ -688,13 +688,9 @@ class MockTimers {
throw new ERR_INVALID_ARG_VALUE('now', internalOptions.now, `epoch must be a positive integer received ${internalOptions.now}`); 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'); validateStringArray(internalOptions.apis, 'options.apis');
// Check that the timers passed are supported // Check that the timers passed are supported

View File

@ -657,7 +657,7 @@ class Test extends AsyncResource {
// - Only called if there are results to report in the correct order. // - Only called if there are results to report in the correct order.
// - Guaranteed to only be called a maximum of once per call to // - Guaranteed to only be called a maximum of once per call to
// processReadySubtestRange(). // processReadySubtestRange().
canSend = canSend || this.isClearToSend(); canSend ||= this.isClearToSend();
if (!canSend) { if (!canSend) {
return; return;

View File

@ -430,9 +430,7 @@ function buildFileTree(summary) {
let current = tree; let current = tree;
ArrayPrototypeForEach(parts, (part, index) => { ArrayPrototypeForEach(parts, (part, index) => {
if (!current[part]) { current[part] ||= { __proto__: null };
current[part] = { __proto__: null };
}
current = current[part]; current = current[part];
// If this is the last part, add the file to the tree // If this is the last part, add the file to the tree
if (index === parts.length - 1) { if (index === parts.length - 1) {

View File

@ -1286,7 +1286,7 @@ function improveStack(stack, constructor, name, tag) {
RegExpPrototypeExec(/^([a-z_A-Z0-9-]*Error)$/, stack); RegExpPrototypeExec(/^([a-z_A-Z0-9-]*Error)$/, stack);
fallback = (start?.[1]) || ''; fallback = (start?.[1]) || '';
len = fallback.length; len = fallback.length;
fallback = fallback || 'Error'; fallback ||= 'Error';
} }
const prefix = StringPrototypeSlice(getPrefix(constructor, tag, fallback), 0, -1); const prefix = StringPrototypeSlice(getPrefix(constructor, tag, fallback), 0, -1);
if (name !== prefix) { if (name !== prefix) {
@ -1941,7 +1941,7 @@ function formatProperty(ctx, value, recurseTimes, key, type, desc,
original = value) { original = value) {
let name, str; let name, str;
let extra = ' '; let extra = ' ';
desc = desc || ObjectGetOwnPropertyDescriptor(value, key) || desc ||= ObjectGetOwnPropertyDescriptor(value, key) ||
{ value: value[key], enumerable: true }; { value: value[key], enumerable: true };
if (desc.value !== undefined) { if (desc.value !== undefined) {
const diff = (ctx.compact !== true || type !== kObjectType) ? 2 : 3; const diff = (ctx.compact !== true || type !== kObjectType) ? 2 : 3;

View File

@ -1045,10 +1045,10 @@ function internalConnect(
if (localAddress || localPort) { if (localAddress || localPort) {
if (addressType === 4) { if (addressType === 4) {
localAddress = localAddress || DEFAULT_IPV4_ADDR; localAddress ||= DEFAULT_IPV4_ADDR;
err = self._handle.bind(localAddress, localPort); err = self._handle.bind(localAddress, localPort);
} else { // addressType === 6 } else { // addressType === 6
localAddress = localAddress || DEFAULT_IPV6_ADDR; localAddress ||= DEFAULT_IPV6_ADDR;
err = self._handle.bind6(localAddress, localPort, flags); err = self._handle.bind6(localAddress, localPort, flags);
} }
debug('connect: binding to localAddress: %s and localPort: %d (addressType: %d)', debug('connect: binding to localAddress: %s and localPort: %d (addressType: %d)',
@ -1445,9 +1445,7 @@ function lookupAndConnectMultiple(
return; return;
} }
if (isIP(ip) && (addressType === 4 || addressType === 6)) { 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]; const destination = destinations[addressType];

View File

@ -225,8 +225,8 @@ function encodeStringifiedCustom(v, encode) {
* @returns {string} * @returns {string}
*/ */
function stringify(obj, sep, eq, options) { function stringify(obj, sep, eq, options) {
sep = sep || '&'; sep ||= '&';
eq = eq || '='; eq ||= '=';
let encode = QueryString.escape; let encode = QueryString.escape;
if (options && typeof options.encodeURIComponent === 'function') { if (options && typeof options.encodeURIComponent === 'function') {

View File

@ -465,8 +465,7 @@ Interface.prototype._moveCursor = _Interface.prototype[kMoveCursor];
Interface.prototype._ttyWrite = _Interface.prototype[kTtyWrite]; Interface.prototype._ttyWrite = _Interface.prototype[kTtyWrite];
function _ttyWriteDumb(s, key) { function _ttyWriteDumb(s, key) {
key = key || kEmptyObject; key ||= kEmptyObject;
if (key.name === 'escape') return; if (key.name === 'escape') return;
if (this[kSawReturnAt] && key.name !== 'enter') if (this[kSawReturnAt] && key.name !== 'enter')

View File

@ -286,10 +286,9 @@ function REPLServer(prompt,
if (!options.input && !options.output) { if (!options.input && !options.output) {
// Legacy API, passing a 'stream'/'socket' option. // Legacy API, passing a 'stream'/'socket' option.
if (!stream) { // Use stdin and stdout as the default streams if none were given.
// Use stdin and stdout as the default streams if none were given. stream ||= process;
stream = process;
}
// We're given a duplex readable/writable Stream, like a `net.Socket` // We're given a duplex readable/writable Stream, like a `net.Socket`
// or a custom object with 2 streams, or the `process` object. // or a custom object with 2 streams, or the `process` object.
options.input = stream.stdin || stream; options.input = stream.stdin || stream;
@ -398,7 +397,7 @@ function REPLServer(prompt,
`${sep}(.*)${sep}(.*)${sep}(.*)${sep}(.*)` + `${sep}(.*)${sep}(.*)${sep}(.*)${sep}(.*)` +
`${sep}(.*)$`); `${sep}(.*)$`);
eval_ = eval_ || defaultEval; eval_ ||= defaultEval;
const self = this; const self = this;
@ -879,7 +878,7 @@ function REPLServer(prompt,
self.on('line', function onLine(cmd) { self.on('line', function onLine(cmd) {
debug('line %j', cmd); debug('line %j', cmd);
cmd = cmd || ''; cmd ||= '';
sawSIGINT = false; sawSIGINT = false;
if (self.editorMode) { if (self.editorMode) {
@ -1007,7 +1006,7 @@ function REPLServer(prompt,
// Wrap readline tty to enable editor mode and pausing. // Wrap readline tty to enable editor mode and pausing.
const ttyWrite = FunctionPrototypeBind(self._ttyWrite, self); const ttyWrite = FunctionPrototypeBind(self._ttyWrite, self);
self._ttyWrite = (d, key) => { self._ttyWrite = (d, key) => {
key = key || {}; key ||= {};
if (paused && !(self.breakEvalOnSigint && key.ctrl && key.name === 'c')) { if (paused && !(self.breakEvalOnSigint && key.ctrl && key.name === 'c')) {
ArrayPrototypePush(pausedBuffer, ArrayPrototypePush(pausedBuffer,
['key', [d, key], self.isCompletionEnabled]); ['key', [d, key], self.isCompletionEnabled]);
@ -1553,9 +1552,7 @@ function complete(line, callback) {
ArrayPrototypeMap(group, ArrayPrototypeMap(group,
(member) => `${expr}${member}`)); (member) => `${expr}${member}`));
}); });
if (filter) { filter &&= `${expr}${filter}`;
filter = `${expr}${filter}`;
}
} }
completionGroupsLoaded(); completionGroupsLoaded();
@ -1645,8 +1642,8 @@ REPLServer.prototype.defineCommand = function(keyword, cmd) {
// sufficient anymore. // sufficient anymore.
function _memory(cmd) { function _memory(cmd) {
const self = this; const self = this;
self.lines = self.lines || []; self.lines ||= [];
self.lines.level = self.lines.level || []; self.lines.level ||= [];
// Save the line so I can do magic later // Save the line so I can do magic later
if (cmd) { if (cmd) {

View File

@ -170,8 +170,7 @@ ObjectDefineProperty(setTimeout, customPromisify, {
__proto__: null, __proto__: null,
enumerable: true, enumerable: true,
get() { get() {
if (!timersPromises) timersPromises ??= require('timers/promises');
timersPromises = require('timers/promises');
return timersPromises.setTimeout; return timersPromises.setTimeout;
}, },
}); });
@ -309,8 +308,7 @@ ObjectDefineProperty(setImmediate, customPromisify, {
__proto__: null, __proto__: null,
enumerable: true, enumerable: true,
get() { get() {
if (!timersPromises) timersPromises ??= require('timers/promises');
timersPromises = require('timers/promises');
return timersPromises.setImmediate; return timersPromises.setImmediate;
}, },
}); });

View File

@ -790,8 +790,8 @@ Url.prototype.resolveObject = function resolveObject(relative) {
!hostlessProtocol.has(relative.protocol)) { !hostlessProtocol.has(relative.protocol)) {
const relPath = (relative.pathname || '').split('/'); const relPath = (relative.pathname || '').split('/');
while (relPath.length && !(relative.host = relPath.shift())); while (relPath.length && !(relative.host = relPath.shift()));
if (!relative.host) relative.host = ''; relative.host ||= '';
if (!relative.hostname) relative.hostname = ''; relative.hostname ||= '';
if (relPath[0] !== '') relPath.unshift(''); if (relPath[0] !== '') relPath.unshift('');
if (relPath.length < 2) relPath.unshift(''); if (relPath.length < 2) relPath.unshift('');
result.pathname = relPath.join('/'); result.pathname = relPath.join('/');
@ -810,7 +810,7 @@ Url.prototype.resolveObject = function resolveObject(relative) {
const s = result.search || ''; const s = result.search || '';
result.path = p + s; result.path = p + s;
} }
result.slashes = result.slashes || relative.slashes; result.slashes ||= relative.slashes;
result.href = result.format(); result.href = result.format();
return result; return result;
} }
@ -850,7 +850,7 @@ Url.prototype.resolveObject = function resolveObject(relative) {
} }
relative.host = null; relative.host = null;
} }
mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); mustEndAbs &&= (relPath[0] === '' || srcPath[0] === '');
} }
if (isRelAbs) { if (isRelAbs) {
@ -871,7 +871,7 @@ Url.prototype.resolveObject = function resolveObject(relative) {
} else if (relPath.length) { } else if (relPath.length) {
// it's relative // it's relative
// throw away the existing file, and take the new path instead. // throw away the existing file, and take the new path instead.
if (!srcPath) srcPath = []; srcPath ||= [];
srcPath.pop(); srcPath.pop();
srcPath = srcPath.concat(relPath); srcPath = srcPath.concat(relPath);
result.search = relative.search; 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) { if (mustEndAbs && !isAbsolute) {
srcPath.unshift(''); srcPath.unshift('');
@ -993,7 +993,7 @@ Url.prototype.resolveObject = function resolveObject(relative) {
(result.search ? result.search : ''); (result.search ? result.search : '');
} }
result.auth = relative.auth || result.auth; result.auth = relative.auth || result.auth;
result.slashes = result.slashes || relative.slashes; result.slashes ||= relative.slashes;
result.href = result.format(); result.href = result.format();
return result; return result;
}; };

View File

@ -146,7 +146,7 @@ class ActivityCollector {
_stamp(h, hook) { _stamp(h, hook) {
if (h == null) return; if (h == null) return;
if (h[hook] == null) h[hook] = []; h[hook] ??= [];
const time = process.hrtime(this._start); const time = process.hrtime(this._start);
h[hook].push((time[0] * 1e9) + time[1]); h[hook].push((time[0] * 1e9) + time[1]);
} }

View File

@ -69,7 +69,7 @@ module.exports = function verifyGraph(hooks, graph) {
activities.forEach(processActivity); activities.forEach(processActivity);
function processActivity(x) { function processActivity(x) {
if (!typeSeen[x.type]) typeSeen[x.type] = 0; typeSeen[x.type] ||= 0;
typeSeen[x.type]++; typeSeen[x.type]++;
const node = findInGraph(graph, x.type, 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) // Verify that all expected types are present (but more/others are allowed)
const expTypes = { __proto__: null }; const expTypes = { __proto__: null };
for (let i = 0; i < graph.length; i++) { 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]++; expTypes[graph[i].type]++;
} }
@ -129,7 +129,7 @@ module.exports.printGraph = function printGraph(hooks) {
function processNode(x) { function processNode(x) {
const key = x.type.replace(/WRAP/, '').toLowerCase(); const key = x.type.replace(/WRAP/, '').toLowerCase();
if (!ids[key]) ids[key] = 1; ids[key] ||= 1;
const id = `${key}:${ids[key]++}`; const id = `${key}:${ids[key]++}`;
uidtoid[x.uid] = id; uidtoid[x.uid] = id;
const triggerAsyncId = uidtoid[x.triggerAsyncId] || null; const triggerAsyncId = uidtoid[x.triggerAsyncId] || null;

View File

@ -13,7 +13,7 @@ function addLibraryPath(env) {
return; return;
} }
env = env || process.env; env ||= process.env;
env.LD_LIBRARY_PATH = env.LD_LIBRARY_PATH =
(env.LD_LIBRARY_PATH ? env.LD_LIBRARY_PATH + path.delimiter : '') + (env.LD_LIBRARY_PATH ? env.LD_LIBRARY_PATH + path.delimiter : '') +

View File

@ -878,22 +878,16 @@ class WPTRunner {
addTestResult(spec, item) { addTestResult(spec, item) {
let result = this.results[spec.filename]; let result = this.results[spec.filename];
if (!result) { result ||= this.results[spec.filename] = {};
result = this.results[spec.filename] = {};
}
if (item.status === kSkip) { if (item.status === kSkip) {
// { filename: { skip: 'reason' } } // { filename: { skip: 'reason' } }
result[kSkip] = item.reason; result[kSkip] = item.reason;
} else { } else {
// { filename: { fail: { expected: [ ... ], // { filename: { fail: { expected: [ ... ],
// unexpected: [ ... ] } }} // unexpected: [ ... ] } }}
if (!result[item.status]) { result[item.status] ||= {};
result[item.status] = {};
}
const key = item.expected ? 'expected' : 'unexpected'; 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); const hasName = result[item.status][key].includes(item.name);
if (!hasName) { if (!hasName) {
result[item.status][key].push(item.name); result[item.status][key].push(item.name);

View File

@ -34,7 +34,7 @@ const server = http.createServer(common.mustCall((req, res) => {
res.writeHead(200); res.writeHead(200);
res.write('foo'); res.write('foo');
complete = complete || function() { complete ??= function() {
res.end(); res.end();
}; };
})); }));

View File

@ -26,7 +26,7 @@ function createLocalConnection(options) {
} }
http.createServer(common.mustCall(function(req, res) { http.createServer(common.mustCall(function(req, res) {
this.requests = this.requests || 0; this.requests ||= 0;
assert.strictEqual(req.headers.host, req.headers.expectedhost); assert.strictEqual(req.headers.host, req.headers.expectedhost);
res.end(); res.end();
if (++this.requests === requests.length) if (++this.requests === requests.length)

View File

@ -256,7 +256,7 @@ function expectBody(expected) {
assert.strictEqual(versionMajor, 1); assert.strictEqual(versionMajor, 1);
assert.strictEqual(versionMinor, 0); assert.strictEqual(versionMinor, 0);
headers = headers || parser.headers; headers ||= parser.headers;
assert.strictEqual(headers.length, 2 * 256); // 256 key/value pairs assert.strictEqual(headers.length, 2 * 256); // 256 key/value pairs
for (let i = 0; i < headers.length; i += 2) { for (let i = 0; i < headers.length; i += 2) {

View File

@ -40,7 +40,7 @@ function verifySecureSession(key, cert, ca, opts) {
server.on('stream', common.mustCall(onStream)); server.on('stream', common.mustCall(onStream));
server.on('close', common.mustCall()); server.on('close', common.mustCall());
server.listen(0, common.mustCall(() => { server.listen(0, common.mustCall(() => {
opts = opts || { }; opts ||= {};
opts.secureContext = tls.createSecureContext({ ca }); opts.secureContext = tls.createSecureContext({ ca });
const client = h2.connect(`https://localhost:${server.address().port}`, const client = h2.connect(`https://localhost:${server.address().port}`,
opts); opts);

View File

@ -36,18 +36,12 @@ function createTimingInfo({
finalConnectionTimingInfo = null finalConnectionTimingInfo = null
}) { }) {
if (finalConnectionTimingInfo !== null) { if (finalConnectionTimingInfo !== null) {
finalConnectionTimingInfo.domainLookupStartTime = finalConnectionTimingInfo.domainLookupStartTime ||= 0;
finalConnectionTimingInfo.domainLookupStartTime || 0; finalConnectionTimingInfo.domainLookupEndTime ||= 0;
finalConnectionTimingInfo.domainLookupEndTime = finalConnectionTimingInfo.connectionStartTime ||= 0;
finalConnectionTimingInfo.domainLookupEndTime || 0; finalConnectionTimingInfo.connectionEndTime ||= 0;
finalConnectionTimingInfo.connectionStartTime = finalConnectionTimingInfo.secureConnectionStartTime ||= 0;
finalConnectionTimingInfo.connectionStartTime || 0; finalConnectionTimingInfo.ALPNNegotiatedProtocol ||= [];
finalConnectionTimingInfo.connectionEndTime =
finalConnectionTimingInfo.connectionEndTime || 0;
finalConnectionTimingInfo.secureConnectionStartTime =
finalConnectionTimingInfo.secureConnectionStartTime || 0;
finalConnectionTimingInfo.ALPNNegotiatedProtocol =
finalConnectionTimingInfo.ALPNNegotiatedProtocol || [];
} }
return { return {
startTime, startTime,

View File

@ -28,10 +28,8 @@ let passed = false;
class TestStream extends stream.Transform { class TestStream extends stream.Transform {
_transform(chunk, encoding, done) { _transform(chunk, encoding, done) {
if (!passed) { // Char 'a' only exists in the last write
// Char 'a' only exists in the last write passed ||= chunk.toString().includes('a');
passed = chunk.toString().includes('a');
}
done(); done();
} }
} }

View File

@ -213,9 +213,7 @@ const { PassThrough, Transform } = require('stream');
pt.state = ''; pt.state = '';
pt._transform = function(chunk, encoding, cb) { pt._transform = function(chunk, encoding, cb) {
if (!chunk) const s = (chunk ||= '').toString();
chunk = '';
const s = chunk.toString();
setTimeout(() => { setTimeout(() => {
this.state += s.charAt(0); this.state += s.charAt(0);
if (this.state.length === 3) { if (this.state.length === 3) {

View File

@ -73,13 +73,9 @@ function testServers(index, servers, clientOptions, cb) {
const ok = serverOptions.ok; 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) { const server = tls.createServer(serverOptions, common.mustCall(function(s) {
s.end('hello world\n'); s.end('hello world\n');

View File

@ -135,7 +135,7 @@ function start(callback) {
connect(); connect();
}); });
s.on('session', (session) => { s.on('session', (session) => {
sess = sess || session; sess ||= session;
}); });
s.once('session', (session) => onNewSession(s, session)); s.once('session', (session) => onNewSession(s, session));
s.once('session', () => ticketLog.push(s.getTLSTicket().toString('hex'))); s.once('session', () => ticketLog.push(s.getTLSTicket().toString('hex')));

View File

@ -9,8 +9,7 @@ function getSource(tag) {
} }
function produce(source, count) { function produce(source, count) {
if (!count) count ||= 1;
count = 1;
const out = spawnSync(process.execPath, [ '-e', ` const out = spawnSync(process.execPath, [ '-e', `
'use strict'; 'use strict';

View File

@ -41,17 +41,17 @@ class RandomReadStream extends Stream {
this._processing = false; this._processing = false;
this._hasher = crypto.createHash('sha1'); this._hasher = crypto.createHash('sha1');
opt = opt || {}; opt ||= {};
// base block size. // base block size.
opt.block = opt.block || 256 * 1024; opt.block ||= 256 * 1024;
// Total number of bytes to emit // Total number of bytes to emit
opt.total = opt.total || 256 * 1024 * 1024; opt.total ||= 256 * 1024 * 1024;
this._remaining = opt.total; this._remaining = opt.total;
// How variable to make the block sizes // How variable to make the block sizes
opt.jitter = opt.jitter || 1024; opt.jitter ||= 1024;
this._opt = opt; this._opt = opt;

View File

@ -20,26 +20,18 @@ export function extractAndParseYAML(text) {
// js-yaml.load() throws on error. // js-yaml.load() throws on error.
const meta = yaml.load(text); const meta = yaml.load(text);
if (meta.added) { // Since semver-minors can trickle down to previous major versions,
// Since semver-minors can trickle down to previous major versions, // features may have been added in multiple versions.
// features may have been added in multiple versions. meta.added &&= arrify(meta.added);
meta.added = arrify(meta.added);
}
if (meta.napiVersion) { meta.napiVersion &&= arrify(meta.napiVersion);
meta.napiVersion = arrify(meta.napiVersion);
}
if (meta.deprecated) { // Treat deprecated like added for consistency.
// Treat deprecated like added for consistency. meta.deprecated &&= arrify(meta.deprecated);
meta.deprecated = arrify(meta.deprecated);
}
if (meta.removed) { meta.removed &&= arrify(meta.removed);
meta.removed = arrify(meta.removed);
}
meta.changes = meta.changes || []; meta.changes ||= [];
return meta; return meta;
} }

View File

@ -72,7 +72,7 @@ async function main() {
} }
} }
nodeVersion = nodeVersion || process.version; nodeVersion ||= process.version;
if (!filename) { if (!filename) {
throw new Error('No input file specified'); throw new Error('No input file specified');

View File

@ -428,8 +428,8 @@ export function buildToc({ filename, apilinks }) {
const isDeprecationHeading = const isDeprecationHeading =
DEPRECATION_HEADING_PATTERN.test(headingText); DEPRECATION_HEADING_PATTERN.test(headingText);
if (isDeprecationHeading) { if (isDeprecationHeading) {
if (!node.data) node.data = {}; node.data ||= {};
if (!node.data.hProperties) node.data.hProperties = {}; node.data.hProperties ||= {};
node.data.hProperties.id = node.data.hProperties.id =
headingText.substring(0, headingText.indexOf(':')); headingText.substring(0, headingText.indexOf(':'));
} }

View File

@ -220,10 +220,10 @@ export function jsonAPI({ filename }) {
// which are actually just descriptions of a constructor class signature. // which are actually just descriptions of a constructor class signature.
// Merge them into the parent. // Merge them into the parent.
if (current.type === 'class' && current.ctors) { if (current.type === 'class' && current.ctors) {
current.signatures = current.signatures || []; current.signatures ||= [];
const sigs = current.signatures; const sigs = current.signatures;
current.ctors.forEach((ctor) => { current.ctors.forEach((ctor) => {
ctor.signatures = ctor.signatures || [{}]; ctor.signatures ||= [{}];
ctor.signatures.forEach((sig) => { ctor.signatures.forEach((sig) => {
sig.desc = ctor.desc; sig.desc = ctor.desc;
}); });
@ -261,8 +261,8 @@ export function jsonAPI({ filename }) {
} }
if (parent[key] && Array.isArray(parent[key])) { if (parent[key] && Array.isArray(parent[key])) {
parent[key] = parent[key].concat(current[key]); parent[key] = parent[key].concat(current[key]);
} else if (!parent[key]) { } else {
parent[key] = current[key]; 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 // Add this section to the parent. Sometimes we have two headings with a
// single blob of description. If the preceding entry at this level // single blob of description. If the preceding entry at this level
// shares a name and is lacking a description, copy it backwards. // 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]; const prev = parent[plur].slice(-1)[0];
if (prev && prev.name === current.name && !prev.desc) { if (prev && prev.name === current.name && !prev.desc) {
prev.desc = current.desc; prev.desc = current.desc;

View File

@ -7,12 +7,10 @@ export function replaceLinks({ filename, linksMapper }) {
const fileHtmlUrls = linksMapper[filename]; const fileHtmlUrls = linksMapper[filename];
visit(tree, (node) => { visit(tree, (node) => {
if (node.url) { node.url &&= node.url.replace(
node.url = node.url.replace( referenceToLocalMdFile,
referenceToLocalMdFile, (_, filename, hash) => `${filename}.html${hash || ''}`,
(_, filename, hash) => `${filename}.html${hash || ''}`, );
);
}
}); });
visit(tree, 'definition', (node) => { visit(tree, 'definition', (node) => {
const htmlUrl = fileHtmlUrls?.[node.identifier]; const htmlUrl = fileHtmlUrls?.[node.identifier];

View File

@ -42,8 +42,7 @@ module.exports = {
break; break;
case ']': case ']':
if (!escaping) { if (!escaping) {
if (inCharClass) inCharClass &&= false;
inCharClass = false;
} else { } else {
escaping = false; escaping = false;
} }
@ -63,8 +62,7 @@ module.exports = {
} }
break; break;
default: default:
if (escaping) escaping &&= false;
escaping = false;
} }
} }
} }

View File

@ -93,8 +93,7 @@ class ParagraphParser extends Stream {
// Strip comments around block // Strip comments around block
if (this.blockIsLicenseBlock) { if (this.blockIsLicenseBlock) {
if (!this.blockHasCStyleComment) this.blockHasCStyleComment ||= /^\s*(\/\*)/.test(line);
this.blockHasCStyleComment = /^\s*(\/\*)/.test(line);
if (this.blockHasCStyleComment) { if (this.blockHasCStyleComment) {
const prev = line; const prev = line;
line = line.replace(/^(\s*?)(?:\s?\*\/|\/\*\s|\s\*\s?)/, '$1'); line = line.replace(/^(\s*?)(?:\s?\*\/|\/\*\s|\s\*\s?)/, '$1');

View File

@ -72,7 +72,7 @@ async function checkFiles(...files) {
await fd.truncate(toWrite.length); await fd.truncate(toWrite.length);
await fd.write(toWrite, 0, toWrite.length, 0); await fd.write(toWrite, 0, toWrite.length, 0);
} else { } else {
if (!process.exitCode) process.exitCode = 1; process.exitCode ||= 1;
console.error( console.error(
(process.env.GITHUB_ACTIONS ? (process.env.GITHUB_ACTIONS ?
`::error file=${file},line=1,col=1::` : `::error file=${file},line=1,col=1::` :