From 91193447fbca4f01fdc7cbb41ce771c3fd928bcf Mon Sep 17 00:00:00 2001 From: Luigi Pinca Date: Wed, 8 Apr 2020 18:58:03 +0200 Subject: [PATCH] tools: enable no-else-return lint rule Refs: https://github.com/nodejs/node/pull/32644 Refs: https://github.com/nodejs/node/pull/32662 PR-URL: https://github.com/nodejs/node/pull/32667 Reviewed-By: Ruben Bridgewater Reviewed-By: Trivikram Kamat --- .eslintrc.js | 1 + benchmark/es/spread-bench.js | 7 ++-- benchmark/scatter.js | 3 +- lib/_http_incoming.js | 3 +- lib/_stream_readable.js | 3 +- lib/_stream_writable.js | 5 +-- lib/_tls_wrap.js | 11 +++-- lib/dns.js | 3 +- lib/events.js | 3 +- lib/fs.js | 3 +- lib/internal/crypto/keys.js | 24 +++++------ lib/internal/crypto/sig.js | 6 +-- lib/internal/errors.js | 27 +++++------- lib/internal/fs/streams.js | 3 +- lib/internal/fs/utils.js | 5 +-- lib/internal/modules/esm/get_source.js | 3 +- lib/internal/modules/esm/resolve.js | 15 +++---- lib/internal/policy/manifest.js | 41 +++++++++---------- lib/internal/source_map/source_map.js | 15 ++++--- lib/internal/source_map/source_map_cache.js | 6 +-- lib/internal/streams/pipeline.js | 5 +-- lib/internal/url.js | 20 ++++----- lib/net.js | 6 +-- lib/repl.js | 3 +- lib/v8.js | 13 +++--- lib/vm.js | 6 +-- lib/zlib.js | 15 ++++--- ...ringbytes-external-exceed-max-by-1-utf8.js | 3 +- test/async-hooks/init-hooks.js | 13 +++--- test/common/dns.js | 17 ++++---- test/common/index.js | 8 ++-- test/common/inspector-helper.js | 3 +- test/common/shared-lib-util.js | 3 +- test/common/wpt.js | 30 +++++++------- test/parallel/test-fs-mkdir-mode-mask.js | 5 +-- test/parallel/test-fs-utimes.js | 15 ++++--- test/parallel/test-net-pingpong.js | 5 +-- ...st-stream2-readable-empty-buffer-no-eof.js | 3 +- test/parallel/test-trace-events-api.js | 3 +- test/pummel/test-net-pingpong.js | 3 +- tools/doc/json.js | 3 +- tools/test-npm-package.js | 3 +- 42 files changed, 158 insertions(+), 214 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 14c53277a19a47..f59f65f8065c58 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -129,6 +129,7 @@ module.exports = { 'no-dupe-else-if': 'error', 'no-duplicate-case': 'error', 'no-duplicate-imports': 'error', + 'no-else-return': ['error', { allowElseIf: true }], 'no-empty-character-class': 'error', 'no-ex-assign': 'error', 'no-extra-boolean-cast': 'error', diff --git a/benchmark/es/spread-bench.js b/benchmark/es/spread-bench.js index ae5b4abbb99c02..284debdfa09ad8 100644 --- a/benchmark/es/spread-bench.js +++ b/benchmark/es/spread-bench.js @@ -16,11 +16,10 @@ function makeTest(count, rest) { return function test(...args) { assert.strictEqual(count, args.length); }; - } else { - return function test() { - assert.strictEqual(count, arguments.length); - }; } + return function test() { + assert.strictEqual(count, arguments.length); + }; } function main({ n, context, count, rest, method }) { diff --git a/benchmark/scatter.js b/benchmark/scatter.js index ecbf8e0041c837..858169d7d68c3b 100644 --- a/benchmark/scatter.js +++ b/benchmark/scatter.js @@ -30,9 +30,8 @@ let printHeader = true; function csvEncodeValue(value) { if (typeof value === 'number') { return value.toString(); - } else { - return `"${value.replace(/"/g, '""')}"`; } + return `"${value.replace(/"/g, '""')}"`; } (function recursive(i) { diff --git a/lib/_http_incoming.js b/lib/_http_incoming.js index 60081279a05e42..02b88dfe87ca85 100644 --- a/lib/_http_incoming.js +++ b/lib/_http_incoming.js @@ -248,9 +248,8 @@ function matchKnownFields(field, lowercased) { } if (lowercased) { return '\u0000' + field; - } else { - return matchKnownFields(field.toLowerCase(), true); } + return matchKnownFields(field.toLowerCase(), true); } // Add the given (field, value) pair to the message // diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js index f39c49867805d3..42429cf63b8207 100644 --- a/lib/_stream_readable.js +++ b/lib/_stream_readable.js @@ -372,8 +372,7 @@ function howMuchToRead(n, state) { // Only flow one buffer at a time. if (state.flowing && state.length) return state.buffer.first().length; - else - return state.length; + return state.length; } if (n <= state.length) return n; diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js index 4b353a52665efa..236e236aa32459 100644 --- a/lib/_stream_writable.js +++ b/lib/_stream_writable.js @@ -298,10 +298,9 @@ Writable.prototype.write = function(chunk, encoding, cb) { process.nextTick(cb, err); errorOrDestroy(this, err, true); return false; - } else { - state.pendingcb++; - return writeOrBuffer(this, state, chunk, encoding, cb); } + state.pendingcb++; + return writeOrBuffer(this, state, chunk, encoding, cb); }; Writable.prototype.cork = function() { diff --git a/lib/_tls_wrap.js b/lib/_tls_wrap.js index 6ffa5c74abb670..8b912d805c5114 100644 --- a/lib/_tls_wrap.js +++ b/lib/_tls_wrap.js @@ -1503,13 +1503,12 @@ function onConnectSecure() { if (options.rejectUnauthorized) { this.destroy(verifyError); return; - } else { - debug('client emit secureConnect. rejectUnauthorized: %s, ' + - 'authorizationError: %s', options.rejectUnauthorized, - this.authorizationError); - this.secureConnecting = false; - this.emit('secureConnect'); } + debug('client emit secureConnect. rejectUnauthorized: %s, ' + + 'authorizationError: %s', options.rejectUnauthorized, + this.authorizationError); + this.secureConnecting = false; + this.emit('secureConnect'); } else { this.authorized = true; debug('client emit secureConnect. authorized:', this.authorized); diff --git a/lib/dns.js b/lib/dns.js index 4243a05e179b88..92b70c73effbf2 100644 --- a/lib/dns.js +++ b/lib/dns.js @@ -261,9 +261,8 @@ function resolve(hostname, rrtype, callback) { if (typeof resolver === 'function') { return resolver.call(this, hostname, callback); - } else { - throw new ERR_INVALID_OPT_VALUE('rrtype', rrtype); } + throw new ERR_INVALID_OPT_VALUE('rrtype', rrtype); } function defaultResolverSetServers(servers) { diff --git a/lib/events.js b/lib/events.js index b138979e138fdf..fc2f969ea37ef6 100644 --- a/lib/events.js +++ b/lib/events.js @@ -577,9 +577,8 @@ EventEmitter.prototype.rawListeners = function rawListeners(type) { EventEmitter.listenerCount = function(emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); } + return listenerCount.call(emitter, type); }; EventEmitter.prototype.listenerCount = listenerCount; diff --git a/lib/fs.js b/lib/fs.js index d08b74db62077d..5883a082921c90 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -1545,9 +1545,8 @@ function encodeRealpathResult(result, options) { const asBuffer = Buffer.from(result); if (options.encoding === 'buffer') { return asBuffer; - } else { - return asBuffer.toString(options.encoding); } + return asBuffer.toString(options.encoding); } // Finds the next portion of a (partial) path, up to the next path delimiter diff --git a/lib/internal/crypto/keys.js b/lib/internal/crypto/keys.js index 087cef014f0fb1..c0a133d5d429a3 100644 --- a/lib/internal/crypto/keys.js +++ b/lib/internal/crypto/keys.js @@ -277,14 +277,13 @@ function prepareAsymmetricKey(key, ctx) { const isPublic = (ctx === kConsumePrivate || ctx === kCreatePrivate) ? false : undefined; return { data, ...parseKeyEncoding(key, undefined, isPublic) }; - } else { - throw new ERR_INVALID_ARG_TYPE( - 'key', - ['string', 'Buffer', 'TypedArray', 'DataView', - ...(ctx !== kCreatePrivate ? ['KeyObject'] : [])], - key - ); } + throw new ERR_INVALID_ARG_TYPE( + 'key', + ['string', 'Buffer', 'TypedArray', 'DataView', + ...(ctx !== kCreatePrivate ? ['KeyObject'] : [])], + key + ); } function preparePrivateKey(key) { @@ -301,13 +300,12 @@ function prepareSecretKey(key, bufferOnly = false) { if (key.type !== 'secret') throw new ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE(key.type, 'secret'); return key[kHandle]; - } else { - throw new ERR_INVALID_ARG_TYPE( - 'key', - ['Buffer', 'TypedArray', 'DataView', - ...(bufferOnly ? [] : ['string', 'KeyObject'])], - key); } + throw new ERR_INVALID_ARG_TYPE( + 'key', + ['Buffer', 'TypedArray', 'DataView', + ...(bufferOnly ? [] : ['string', 'KeyObject'])], + key); } return key; } diff --git a/lib/internal/crypto/sig.js b/lib/internal/crypto/sig.js index 7e3b7aa7ff394d..a7c7b71e35619d 100644 --- a/lib/internal/crypto/sig.js +++ b/lib/internal/crypto/sig.js @@ -77,8 +77,7 @@ function getDSASignatureEncoding(options) { return kSigEncDER; else if (dsaEncoding === 'ieee-p1363') return kSigEncP1363; - else - throw new ERR_INVALID_OPT_VALUE('dsaEncoding', dsaEncoding); + throw new ERR_INVALID_OPT_VALUE('dsaEncoding', dsaEncoding); } return kSigEncDER; @@ -89,9 +88,8 @@ function getIntOption(name, options) { if (value !== undefined) { if (value === value >> 0) { return value; - } else { - throw new ERR_INVALID_OPT_VALUE(name, value); } + throw new ERR_INVALID_OPT_VALUE(name, value); } return undefined; } diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 61fdf2ff7b4a5f..f20577f8bc66af 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -1090,10 +1090,9 @@ E('ERR_INVALID_MODULE_SPECIFIER', (pkgPath, subpath, base = undefined) => { assert(subpath !== '.'); return `Package subpath '${subpath}' is not a valid module request for ` + `the "exports" resolution of ${pkgPath}${sep}package.json`; - } else { - return `Package subpath '${subpath}' is not a valid module request for ` + - `the "exports" resolution of ${pkgPath} imported from ${base}`; } + return `Package subpath '${subpath}' is not a valid module request for ` + + `the "exports" resolution of ${pkgPath} imported from ${base}`; }, TypeError); E('ERR_INVALID_OPT_VALUE', (name, value) => `The value "${String(value)}" is invalid for option "${name}"`, @@ -1104,8 +1103,7 @@ E('ERR_INVALID_OPT_VALUE_ENCODING', E('ERR_INVALID_PACKAGE_CONFIG', (path, message, hasMessage = true) => { if (hasMessage) return `Invalid package config ${path}${sep}package.json, ${message}`; - else - return `Invalid JSON in ${path} imported from ${message}`; + return `Invalid JSON in ${path} imported from ${message}`; }, Error); E('ERR_INVALID_PACKAGE_TARGET', (pkgPath, key, subpath, target, base = undefined) => { @@ -1116,11 +1114,10 @@ E('ERR_INVALID_PACKAGE_TARGET', return `Invalid "exports" target ${JSONStringify(target)} defined ` + `for '${subpath}' in the package config ${pkgPath} imported from ` + `${base}.${relError ? '; targets must start with "./"' : ''}`; - } else { - return `Invalid "exports" main target ${target} defined in the ` + - `package config ${pkgPath} imported from ${base}${relError ? - '; targets must start with "./"' : ''}`; } + return `Invalid "exports" main target ${target} defined in the ` + + `package config ${pkgPath} imported from ${base}${relError ? + '; targets must start with "./"' : ''}`; } else if (key === '.') { return `Invalid "exports" main target ${JSONStringify(target)} defined ` + `in the package config ${pkgPath}${sep}package.json${relError ? @@ -1130,11 +1127,10 @@ E('ERR_INVALID_PACKAGE_TARGET', StringPrototypeSlice(key, 0, -subpath.length || key.length)}' in the ` + `package config ${pkgPath}${sep}package.json; ` + 'targets must start with "./"'; - } else { - return `Invalid "exports" target ${JSONStringify(target)} defined for '${ - StringPrototypeSlice(key, 0, -subpath.length || key.length)}' in the ` + - `package config ${pkgPath}${sep}package.json`; } + return `Invalid "exports" target ${JSONStringify(target)} defined for '${ + StringPrototypeSlice(key, 0, -subpath.length || key.length)}' in the ` + + `package config ${pkgPath}${sep}package.json`; }, Error); E('ERR_INVALID_PERFORMANCE_MARK', 'The "%s" performance mark has not been set', Error); @@ -1289,10 +1285,9 @@ E('ERR_PACKAGE_PATH_NOT_EXPORTED', (pkgPath, subpath, base = undefined) => { } else if (base === undefined) { return `Package subpath '${subpath}' is not defined by "exports" in ${ pkgPath}${sep}package.json`; - } else { - return `Package subpath '${subpath}' is not defined by "exports" in ${ - pkgPath} imported from ${base}`; } + return `Package subpath '${subpath}' is not defined by "exports" in ${ + pkgPath} imported from ${base}`; }, Error); E('ERR_REQUIRE_ESM', (filename, parentPath = null, packageJsonPath = null) => { diff --git a/lib/internal/fs/streams.js b/lib/internal/fs/streams.js index 2f5f8948eea458..2466432cb03e54 100644 --- a/lib/internal/fs/streams.js +++ b/lib/internal/fs/streams.js @@ -478,9 +478,8 @@ WriteStream.prototype.close = function(cb) { if (this.closed) { process.nextTick(cb); return; - } else { - this.on('close', cb); } + this.on('close', cb); } // If we are not autoClosing, we should call diff --git a/lib/internal/fs/utils.js b/lib/internal/fs/utils.js index b91eaa006c44cf..96be328a8ea2fc 100644 --- a/lib/internal/fs/utils.js +++ b/lib/internal/fs/utils.js @@ -301,10 +301,9 @@ function preprocessSymlinkDestination(path, type, linkPath) { // A relative target is relative to the link's parent directory. path = pathModule.resolve(linkPath, '..', path); return pathModule.toNamespacedPath(path); - } else { - // Windows symlinks don't tolerate forward slashes. - return ('' + path).replace(/\//g, '\\'); } + // Windows symlinks don't tolerate forward slashes. + return ('' + path).replace(/\//g, '\\'); } // Constructor for file stats. diff --git a/lib/internal/modules/esm/get_source.js b/lib/internal/modules/esm/get_source.js index 18af566df90ae3..7b2a2f42eabed9 100644 --- a/lib/internal/modules/esm/get_source.js +++ b/lib/internal/modules/esm/get_source.js @@ -28,8 +28,7 @@ async function defaultGetSource(url, { format } = {}, defaultGetSource) { return { source: Buffer.from(body, base64 ? 'base64' : 'utf8') }; - } else { - throw new ERR_INVALID_URL_SCHEME(['file', 'data']); } + throw new ERR_INVALID_URL_SCHEME(['file', 'data']); } exports.defaultGetSource = defaultGetSource; diff --git a/lib/internal/modules/esm/resolve.js b/lib/internal/modules/esm/resolve.js index cbcdb020ed7cd3..29235a6785f1bc 100644 --- a/lib/internal/modules/esm/resolve.js +++ b/lib/internal/modules/esm/resolve.js @@ -455,10 +455,9 @@ function packageMainResolve(packageJSONUrl, packageConfig, base, conditions) { if (packageConfig.main !== undefined) { return finalizeResolution( new URL(packageConfig.main, packageJSONUrl), base); - } else { - return finalizeResolution( - new URL('index', packageJSONUrl), base); } + return finalizeResolution( + new URL('index', packageJSONUrl), base); } return legacyMainResolve(packageJSONUrl, packageConfig); } @@ -578,10 +577,9 @@ function packageResolve(specifier, base, conditions) { } else if (packageSubpath === '') { return packageMainResolve(packageJSONUrl, packageConfig, base, conditions); - } else { - return packageExportsResolve( - packageJSONUrl, packageSubpath, packageConfig, base, conditions); } + return packageExportsResolve( + packageJSONUrl, packageSubpath, packageConfig, base, conditions); } } @@ -611,10 +609,9 @@ function packageResolve(specifier, base, conditions) { } else if (packageConfig.exports !== undefined) { return packageExportsResolve( packageJSONUrl, packageSubpath, packageConfig, base, conditions); - } else { - return finalizeResolution( - new URL(packageSubpath, packageJSONUrl), base); } + return finalizeResolution( + new URL(packageSubpath, packageJSONUrl), base); // Cross-platform root check. } while (packageJSONPath.length !== lastPath.length); diff --git a/lib/internal/policy/manifest.js b/lib/internal/policy/manifest.js index 02cf0743d728cd..ae5e6cd3f43dfd 100644 --- a/lib/internal/policy/manifest.js +++ b/lib/internal/policy/manifest.js @@ -145,32 +145,31 @@ class Manifest { const dependencyRedirectList = (toSpecifier) => { if (toSpecifier in dependencyMap !== true) { return null; - } else { - const to = dependencyMap[toSpecifier]; - if (to === true) { - return true; - } - if (parsedURLs.has(to)) { - return parsedURLs.get(to); - } else if (canBeRequiredByUsers(to)) { - const href = `node:${to}`; - const resolvedURL = new URL(href); - parsedURLs.set(to, resolvedURL); - parsedURLs.set(href, resolvedURL); - return resolvedURL; - } else if (RegExpPrototypeTest(kRelativeURLStringPattern, to)) { - const resolvedURL = new URL(to, manifestURL); - const href = resourceURL.href; - parsedURLs.set(to, resolvedURL); - parsedURLs.set(href, resolvedURL); - return resolvedURL; - } - const resolvedURL = new URL(to); + } + const to = dependencyMap[toSpecifier]; + if (to === true) { + return true; + } + if (parsedURLs.has(to)) { + return parsedURLs.get(to); + } else if (canBeRequiredByUsers(to)) { + const href = `node:${to}`; + const resolvedURL = new URL(href); + parsedURLs.set(to, resolvedURL); + parsedURLs.set(href, resolvedURL); + return resolvedURL; + } else if (RegExpPrototypeTest(kRelativeURLStringPattern, to)) { + const resolvedURL = new URL(to, manifestURL); const href = resourceURL.href; parsedURLs.set(to, resolvedURL); parsedURLs.set(href, resolvedURL); return resolvedURL; } + const resolvedURL = new URL(to); + const href = resourceURL.href; + parsedURLs.set(to, resolvedURL); + parsedURLs.set(href, resolvedURL); + return resolvedURL; }; dependencies.set(resourceHREF, dependencyRedirectList); } else if (dependencyMap === true) { diff --git a/lib/internal/source_map/source_map.js b/lib/internal/source_map/source_map.js index 35ec3ae740e887..2cd70c5c944e19 100644 --- a/lib/internal/source_map/source_map.js +++ b/lib/internal/source_map/source_map.js @@ -196,15 +196,14 @@ class SourceMap { return {}; } else if (!entry) { return {}; - } else { - return { - generatedLine: entry[0], - generatedColumn: entry[1], - originalSource: entry[2], - originalLine: entry[3], - originalColumn: entry[4] - }; } + return { + generatedLine: entry[0], + generatedColumn: entry[1], + originalSource: entry[2], + originalLine: entry[3], + originalColumn: entry[4] + }; } /** diff --git a/lib/internal/source_map/source_map_cache.js b/lib/internal/source_map/source_map_cache.js index b64af7eed6e097..06b1a2a5f52289 100644 --- a/lib/internal/source_map/source_map_cache.js +++ b/lib/internal/source_map/source_map_cache.js @@ -192,9 +192,8 @@ function sourceMapCacheToObject() { if (ObjectKeys(obj).length === 0) { return undefined; - } else { - return obj; } + return obj; } // Since WeakMap can't be iterated over, we use Module._cache's @@ -243,9 +242,8 @@ function findSourceMap(uri, error) { } if (sourceMap && sourceMap.data) { return new SourceMap(sourceMap.data); - } else { - return undefined; } + return undefined; } module.exports = { diff --git a/lib/internal/streams/pipeline.js b/lib/internal/streams/pipeline.js index cf9d7868916a9e..4786b906f4324c 100644 --- a/lib/internal/streams/pipeline.js +++ b/lib/internal/streams/pipeline.js @@ -107,10 +107,9 @@ function makeAsyncIterable(val) { } else if (isReadable(val)) { // Legacy streams are not Iterable. return fromReadable(val); - } else { - throw new ERR_INVALID_ARG_TYPE( - 'val', ['Readable', 'Iterable', 'AsyncIterable'], val); } + throw new ERR_INVALID_ARG_TYPE( + 'val', ['Readable', 'Iterable', 'AsyncIterable'], val); } async function* fromReadable(val) { diff --git a/lib/internal/url.js b/lib/internal/url.js index efb842a074d750..78f5b32745a043 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js @@ -228,9 +228,8 @@ class URLSearchParams { return `${this.constructor.name} {\n ${output.join(',\n ')} }`; } else if (output.length) { return `${this.constructor.name} { ${output.join(separator)} }`; - } else { - return `${this.constructor.name} {}`; } + return `${this.constructor.name} {}`; } } @@ -1315,16 +1314,15 @@ function getPathFromURLWin32(url) { // already taken care of that for us. Note that this only // causes IDNs with an appropriate `xn--` prefix to be decoded. return `\\\\${domainToUnicode(hostname)}${pathname}`; - } else { - // Otherwise, it's a local path that requires a drive letter - const letter = pathname.codePointAt(1) | 0x20; - const sep = pathname[2]; - if (letter < CHAR_LOWERCASE_A || letter > CHAR_LOWERCASE_Z || // a..z A..Z - (sep !== ':')) { - throw new ERR_INVALID_FILE_URL_PATH('must be absolute'); - } - return pathname.slice(1); } + // Otherwise, it's a local path that requires a drive letter + const letter = pathname.codePointAt(1) | 0x20; + const sep = pathname[2]; + if (letter < CHAR_LOWERCASE_A || letter > CHAR_LOWERCASE_Z || // a..z A..Z + (sep !== ':')) { + throw new ERR_INVALID_FILE_URL_PATH('must be absolute'); + } + return pathname.slice(1); } function getPathFromURLPosix(url) { diff --git a/lib/net.js b/lib/net.js index ee0ffebe0ec45e..ff9a37be360467 100644 --- a/lib/net.js +++ b/lib/net.js @@ -541,9 +541,8 @@ ObjectDefineProperty(Socket.prototype, 'readyState', { return 'readOnly'; } else if (!this.readable && this.writable) { return 'writeOnly'; - } else { - return 'closed'; } + return 'closed'; } }); @@ -1520,9 +1519,8 @@ Server.prototype.address = function() { return out; } else if (this._pipeName) { return this._pipeName; - } else { - return null; } + return null; }; function onconnection(err, clientHandle) { diff --git a/lib/repl.js b/lib/repl.js index bd7b80a91b57ea..3722d50533bf87 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -786,9 +786,8 @@ function REPLServer(prompt, self[kBufferedCommandSymbol] += cmd + '\n'; self.displayPrompt(); return; - } else { - self._domain.emit('error', e.err || e); } + self._domain.emit('error', e.err || e); } // Clear buffer if no SyntaxErrors diff --git a/lib/v8.js b/lib/v8.js index 11ca7fa640f27b..56e3e6056214ca 100644 --- a/lib/v8.js +++ b/lib/v8.js @@ -240,14 +240,13 @@ class DefaultDeserializer extends Deserializer { return new ctor(this.buffer.buffer, offset, byteLength / BYTES_PER_ELEMENT); - } else { - // Copy to an aligned buffer first. - const buffer_copy = Buffer.allocUnsafe(byteLength); - copy(this.buffer, buffer_copy, 0, byteOffset, byteOffset + byteLength); - return new ctor(buffer_copy.buffer, - buffer_copy.byteOffset, - byteLength / BYTES_PER_ELEMENT); } + // Copy to an aligned buffer first. + const buffer_copy = Buffer.allocUnsafe(byteLength); + copy(this.buffer, buffer_copy, 0, byteOffset, byteOffset + byteLength); + return new ctor(buffer_copy.buffer, + buffer_copy.byteOffset, + byteLength / BYTES_PER_ELEMENT); } } diff --git a/lib/vm.js b/lib/vm.js index 57d5d60cf5bb66..ddd70fcbe5abce 100644 --- a/lib/vm.js +++ b/lib/vm.js @@ -127,9 +127,8 @@ class Script extends ContextifyScript { const { breakOnSigint, args } = getRunInContextArgs(options); if (breakOnSigint && process.listenerCount('SIGINT') > 0) { return sigintHandlersWrap(super.runInThisContext, this, args); - } else { - return super.runInThisContext(...args); } + return super.runInThisContext(...args); } runInContext(contextifiedObject, options) { @@ -138,9 +137,8 @@ class Script extends ContextifyScript { if (breakOnSigint && process.listenerCount('SIGINT') > 0) { return sigintHandlersWrap(super.runInContext, this, [contextifiedObject, ...args]); - } else { - return super.runInContext(contextifiedObject, ...args); } + return super.runInContext(contextifiedObject, ...args); } runInNewContext(contextObject, options) { diff --git a/lib/zlib.js b/lib/zlib.js index be8f9401a310d0..1c317af46d1f20 100644 --- a/lib/zlib.js +++ b/lib/zlib.js @@ -762,15 +762,14 @@ function createConvenienceMethod(ctor, sync) { return function syncBufferWrapper(buffer, opts) { return zlibBufferSync(new ctor(opts), buffer); }; - } else { - return function asyncBufferWrapper(buffer, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - return zlibBuffer(new ctor(opts), buffer, callback); - }; } + return function asyncBufferWrapper(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new ctor(opts), buffer, callback); + }; } const kMaxBrotliParam = MathMax(...ObjectKeys(constants).map((key) => { diff --git a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-utf8.js b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-utf8.js index 2ca7050d8ab4ea..78e73e0dc8557b 100644 --- a/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-utf8.js +++ b/test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-utf8.js @@ -38,9 +38,8 @@ assert.throws(() => { name: 'Error' })(e); return true; - } else { - return true; } + return true; }); assert.throws(() => { diff --git a/test/async-hooks/init-hooks.js b/test/async-hooks/init-hooks.js index b10ec827198f6d..59ecc96b881a5a 100644 --- a/test/async-hooks/init-hooks.js +++ b/test/async-hooks/init-hooks.js @@ -165,14 +165,13 @@ class ActivityCollector { // Worker threads start main script execution inside of an AsyncWrap // callback, so we don't yield errors for these. return null; - } else { - const err = new Error(`Found a handle whose ${hook}` + - ' hook was invoked but not its init hook'); - // Don't throw if we see invocations due to an assertion in a test - // failing since we want to list the assertion failure instead - if (/process\._fatalException/.test(err.stack)) return null; - throw err; } + const err = new Error(`Found a handle whose ${hook}` + + ' hook was invoked but not its init hook'); + // Don't throw if we see invocations due to an assertion in a test + // failing since we want to list the assertion failure instead + if (/process\._fatalException/.test(err.stack)) return null; + throw err; } return h; } diff --git a/test/common/dns.js b/test/common/dns.js index 37f80dde02782c..d8a703cc53be86 100644 --- a/test/common/dns.js +++ b/test/common/dns.js @@ -36,16 +36,15 @@ function readDomainFromPacket(buffer, offset) { nread: 1 + length + nread, domain: domain ? `${chunk}.${domain}` : chunk }; - } else { - // Pointer to another part of the packet. - assert.strictEqual(length & 0xC0, 0xC0); - // eslint-disable-next-line space-infix-ops, space-unary-ops - const pointeeOffset = buffer.readUInt16BE(offset) &~ 0xC000; - return { - nread: 2, - domain: readDomainFromPacket(buffer, pointeeOffset) - }; } + // Pointer to another part of the packet. + assert.strictEqual(length & 0xC0, 0xC0); + // eslint-disable-next-line space-infix-ops, space-unary-ops + const pointeeOffset = buffer.readUInt16BE(offset) &~ 0xC000; + return { + nread: 2, + domain: readDomainFromPacket(buffer, pointeeOffset) + }; } function parseDNSPacket(buffer) { diff --git a/test/common/index.js b/test/common/index.js index a75287499263b7..6343425858d8c7 100644 --- a/test/common/index.js +++ b/test/common/index.js @@ -309,10 +309,9 @@ function runCallChecks(exitCode) { if ('minimum' in context) { context.messageSegment = `at least ${context.minimum}`; return context.actual < context.minimum; - } else { - context.messageSegment = `exactly ${context.exact}`; - return context.actual !== context.exact; } + context.messageSegment = `exactly ${context.exact}`; + return context.actual !== context.exact; }); failed.forEach(function(context) { @@ -465,9 +464,8 @@ function nodeProcessAborted(exitCode, signal) { // the expected exit codes or signals. if (signal !== null) { return expectedSignals.includes(signal); - } else { - return expectedExitCodes.includes(exitCode); } + return expectedExitCodes.includes(exitCode); } function isAlive(pid) { diff --git a/test/common/inspector-helper.js b/test/common/inspector-helper.js index d430137746dd81..77d7928af135a6 100644 --- a/test/common/inspector-helper.js +++ b/test/common/inspector-helper.js @@ -217,9 +217,8 @@ class InspectorSession { return Promise .all(commands.map((command) => this._sendMessage(command))) .then(() => {}); - } else { - return this._sendMessage(commands); } + return this._sendMessage(commands); } waitForNotification(methodOrPredicate, description) { diff --git a/test/common/shared-lib-util.js b/test/common/shared-lib-util.js index e522a71b4748d8..9f891a6043ef3d 100644 --- a/test/common/shared-lib-util.js +++ b/test/common/shared-lib-util.js @@ -36,9 +36,8 @@ function getSharedLibPath() { return path.join(kExecPath, 'node.dll'); } else if (common.isOSX) { return path.join(kExecPath, `libnode.${kShlibSuffix}`); - } else { - return path.join(kExecPath, 'lib.target', `libnode.${kShlibSuffix}`); } + return path.join(kExecPath, 'lib.target', `libnode.${kShlibSuffix}`); } // Get the binary path of stack frames. diff --git a/test/common/wpt.js b/test/common/wpt.js index e33d0c86cc7ed9..e79bd66b370735 100644 --- a/test/common/wpt.js +++ b/test/common/wpt.js @@ -73,9 +73,8 @@ class ResourceLoader { text() { return data.toString(); } }; }); - } else { - return fs.readFileSync(file, 'utf8'); } + return fs.readFileSync(file, 'utf8'); } } @@ -603,24 +602,23 @@ class WPTRunner { const matches = code.match(/\/\/ META: .+/g); if (!matches) { return {}; - } else { - const result = {}; - for (const match of matches) { - const parts = match.match(/\/\/ META: ([^=]+?)=(.+)/); - const key = parts[1]; - const value = parts[2]; - if (key === 'script') { - if (result[key]) { - result[key].push(value); - } else { - result[key] = [value]; - } + } + const result = {}; + for (const match of matches) { + const parts = match.match(/\/\/ META: ([^=]+?)=(.+)/); + const key = parts[1]; + const value = parts[2]; + if (key === 'script') { + if (result[key]) { + result[key].push(value); } else { - result[key] = value; + result[key] = [value]; } + } else { + result[key] = value; } - return result; } + return result; } buildQueue() { diff --git a/test/parallel/test-fs-mkdir-mode-mask.js b/test/parallel/test-fs-mkdir-mode-mask.js index 515b982054b82b..40bd7bec441373 100644 --- a/test/parallel/test-fs-mkdir-mode-mask.js +++ b/test/parallel/test-fs-mkdir-mode-mask.js @@ -7,15 +7,12 @@ const assert = require('assert'); const path = require('path'); const fs = require('fs'); -let mode; - if (common.isWindows) { common.skip('mode is not supported in mkdir on Windows'); return; -} else { - mode = 0o644; } +const mode = 0o644; const maskToIgnore = 0o10000; const tmpdir = require('../common/tmpdir'); diff --git a/test/parallel/test-fs-utimes.js b/test/parallel/test-fs-utimes.js index c5ed73733c5c40..b72d263cf6ce50 100644 --- a/test/parallel/test-fs-utimes.js +++ b/test/parallel/test-fs-utimes.js @@ -31,15 +31,14 @@ tmpdir.refresh(); function stat_resource(resource) { if (typeof resource === 'string') { return fs.statSync(resource); - } else { - const stats = fs.fstatSync(resource); - // Ensure mtime has been written to disk - // except for directories on AIX where it cannot be synced - if (common.isAIX && stats.isDirectory()) - return stats; - fs.fsyncSync(resource); - return fs.fstatSync(resource); } + const stats = fs.fstatSync(resource); + // Ensure mtime has been written to disk + // except for directories on AIX where it cannot be synced + if (common.isAIX && stats.isDirectory()) + return stats; + fs.fsyncSync(resource); + return fs.fstatSync(resource); } function check_mtime(resource, mtime) { diff --git a/test/parallel/test-net-pingpong.js b/test/parallel/test-net-pingpong.js index 99a02eda22fb1d..e87ee10e43df84 100644 --- a/test/parallel/test-net-pingpong.js +++ b/test/parallel/test-net-pingpong.js @@ -103,10 +103,9 @@ function pingPongTest(port, host) { assert.strictEqual(client.writable, false); assert.strictEqual(client.readable, true); return; - } else { - assert.strictEqual(client.writable, true); - assert.strictEqual(client.readable, true); } + assert.strictEqual(client.writable, true); + assert.strictEqual(client.readable, true); if (count < N) { client.write('PING'); diff --git a/test/parallel/test-stream2-readable-empty-buffer-no-eof.js b/test/parallel/test-stream2-readable-empty-buffer-no-eof.js index f1e74ad949c590..7be2c358eedd95 100644 --- a/test/parallel/test-stream2-readable-empty-buffer-no-eof.js +++ b/test/parallel/test-stream2-readable-empty-buffer-no-eof.js @@ -95,8 +95,7 @@ function test2() { r._read = function(n) { if (!reads--) return r.push(null); // EOF - else - return r.push(Buffer.from('x')); + return r.push(Buffer.from('x')); }; const results = []; diff --git a/test/parallel/test-trace-events-api.js b/test/parallel/test-trace-events-api.js index 676e7f31e13710..e45f374bab642c 100644 --- a/test/parallel/test-trace-events-api.js +++ b/test/parallel/test-trace-events-api.js @@ -25,9 +25,8 @@ function getEnabledCategoriesFromCommandLine() { const indexOfCatFlag = process.execArgv.indexOf('--trace-event-categories'); if (indexOfCatFlag === -1) { return undefined; - } else { - return process.execArgv[indexOfCatFlag + 1]; } + return process.execArgv[indexOfCatFlag + 1]; } const isChild = process.argv[2] === 'child'; diff --git a/test/pummel/test-net-pingpong.js b/test/pummel/test-net-pingpong.js index b9507d519d8e6d..f21160a1fa2a4d 100644 --- a/test/pummel/test-net-pingpong.js +++ b/test/pummel/test-net-pingpong.js @@ -88,9 +88,8 @@ function pingPongTest(host, on_complete) { if (sent_final_ping) { assert.strictEqual(client.readyState, 'readOnly'); return; - } else { - assert.strictEqual(client.readyState, 'open'); } + assert.strictEqual(client.readyState, 'open'); if (count < N) { client.write('PING'); diff --git a/tools/doc/json.js b/tools/doc/json.js index 94241d9903ef45..66e07b3512befb 100644 --- a/tools/doc/json.js +++ b/tools/doc/json.js @@ -508,8 +508,7 @@ function textJoin(nodes, file) { return `_${textJoin(node.children, file)}_`; } else if (node.children) { return textJoin(node.children, file); - } else { - return node.value; } + return node.value; }).join(''); } diff --git a/tools/test-npm-package.js b/tools/test-npm-package.js index b34b8183677211..392d9feaa1938e 100755 --- a/tools/test-npm-package.js +++ b/tools/test-npm-package.js @@ -32,9 +32,8 @@ function spawnCopyDeepSync(source, destination) { if (common.isWindows) { mkdirSync(destination); // Prevent interactive prompt return spawnSync('xcopy.exe', ['/E', source, destination]); - } else { - return spawnSync('cp', ['-r', `${source}/`, destination]); } + return spawnSync('cp', ['-r', `${source}/`, destination]); } function runNPMPackageTests({ srcDir, install, rebuild, testArgs, logfile }) {