From 979a30e93852dfd15f44d8091a799afb35da6a09 Mon Sep 17 00:00:00 2001 From: Dorian Niemiec Date: Thu, 29 Aug 2024 19:15:07 +0200 Subject: [PATCH] Replace var's with let's and const's --- src/handlers/noproxyHandler.js | 4 +- src/handlers/proxyHandler.js | 4 +- src/index.js | 37 +++++++++---------- .../nonStandardCodesAndHttpAuthentication.js | 4 +- src/middleware/redirects.js | 12 +++--- src/middleware/responseHeaders.js | 2 +- src/middleware/rewriteURL.js | 4 +- .../staticFileServingAndDirectoryListings.js | 8 ++-- src/utils/generateErrorStack.js | 10 ++--- src/utils/getOS.js | 6 +-- src/utils/ipBlockList.js | 2 +- src/utils/ipSubnetUtils.js | 4 +- src/utils/serverconsole.js | 2 +- 13 files changed, 49 insertions(+), 50 deletions(-) diff --git a/src/handlers/noproxyHandler.js b/src/handlers/noproxyHandler.js index 205b45f..1f5f126 100644 --- a/src/handlers/noproxyHandler.js +++ b/src/handlers/noproxyHandler.js @@ -29,8 +29,8 @@ function noproxyHandler(req, socket, head) { // SVR.JS configuration object (modified) const config = deepClone(process.serverConfig); - var reqip = socket.remoteAddress; - var reqport = socket.remotePort; + const reqip = socket.remoteAddress; + const reqport = socket.remotePort; process.reqcounter++; logFacilities.locmessage( `Somebody connected to ${ diff --git a/src/handlers/proxyHandler.js b/src/handlers/proxyHandler.js index 4bf8f9d..f3e60bf 100644 --- a/src/handlers/proxyHandler.js +++ b/src/handlers/proxyHandler.js @@ -36,8 +36,8 @@ function proxyHandler(req, socket, head) { return generateServerString(config.exposeServerVersion); }; - var reqip = socket.remoteAddress; - var reqport = socket.remotePort; + const reqip = socket.remoteAddress; + const reqport = socket.remotePort; process.reqcounter++; logFacilities.locmessage( `Somebody connected to ${ diff --git a/src/index.js b/src/index.js index 41b8452..7d0e436 100644 --- a/src/index.js +++ b/src/index.js @@ -422,7 +422,7 @@ try { } catch (err) { ifaceEx = err; } -var ips = []; +let ips = []; const brdIPs = ["255.255.255.255", "127.255.255.255", "0.255.255.255"]; const netIPs = ["127.0.0.0"]; @@ -461,7 +461,7 @@ if (ips.length == 0) { } // Server IP address -var host = ips[ips.length - 1]; +let host = ips[ips.length - 1]; if (!host) host = "[offline]"; // Public IP address-related @@ -1132,7 +1132,7 @@ if (process.serverConfig.secure) { key: sniCredentialsSingle.key, }); try { - var snMatches = sniCredentialsSingle.name.match( + let snMatches = sniCredentialsSingle.name.match( /^([^:[]*|\[[^]]*\]?)((?::.*)?)$/, ); if (!snMatches[1][0].match(/^\.+$/)) @@ -1414,7 +1414,7 @@ function SVRJSFork() { "Starting next thread, because previous one hung up/crashed...", ); // Fork new worker - var newWorker = {}; + let newWorker = {}; try { if ( !threadLimitWarned && @@ -1518,7 +1518,7 @@ function getWorkerCountToFork() { } function forkWorkers(workersToFork, callback) { - for (var i = 0; i < workersToFork; i++) { + for (let i = 0; i < workersToFork; i++) { if (i == 0) { SVRJSFork(); } else { @@ -1582,9 +1582,9 @@ function msgListener(message) { // Save configuration file function saveConfig() { - for (var i = 0; i < 3; i++) { + for (let i = 0; i < 3; i++) { try { - var configJSONobj = {}; + let configJSONobj = {}; if (fs.existsSync(process.dirname + "/config.json")) configJSONobj = JSON.parse( fs.readFileSync(process.dirname + "/config.json").toString(), @@ -1674,12 +1674,11 @@ function saveConfig() { if (configJSONobj.optOutOfStatisticsServer === undefined) configJSONobj.optOutOfStatisticsServer = false; - var configString = JSON.stringify(configJSONobj, null, 2) + "\n"; - fs.writeFileSync(__dirname + "/config.json", configString); + fs.writeFileSync(__dirname + "/config.json", JSON.stringify(configJSONobj, null, 2) + "\n"); break; } catch (err) { if (i >= 2) throw err; - var now = Date.now(); + const now = Date.now(); while (Date.now() - now < 2); } } @@ -1967,8 +1966,8 @@ function start(init) { }, 300000); } else if (cluster.isPrimary) { setInterval(() => { - var allWorkers = Object.keys(cluster.workers); - var goodWorkers = []; + let allWorkers = Object.keys(cluster.workers); + let goodWorkers = []; const checkWorker = (callback, _id) => { if (typeof _id === "undefined") _id = 0; @@ -2058,8 +2057,8 @@ function start(init) { commands[line.split(" ")[0]] !== undefined && commands[line.split(" ")[0]] !== null ) { - var argss = line.split(" "); - var command = argss.shift(); + let argss = line.split(" "); + const command = argss.shift(); commands[command](argss, (msg) => process.send(msg)); process.send("\x12END"); } else { @@ -2087,15 +2086,15 @@ function start(init) { const command = argss.shift(); if (line != "") { if (cluster.isPrimary !== undefined) { - var allWorkers = Object.keys(cluster.workers); + let allWorkers = Object.keys(cluster.workers); if (command == "block") commands.block(argss, serverconsole.climessage); if (command == "unblock") commands.unblock(argss, serverconsole.climessage); if (command == "restart") { - var stopError = false; + let stopError = false; exiting = true; - for (var i = 0; i < allWorkers.length; i++) { + for (let i = 0; i < allWorkers.length; i++) { try { if (cluster.workers[allWorkers[i]]) { cluster.workers[allWorkers[i]].kill(); @@ -2224,7 +2223,7 @@ function start(init) { !process.serverConfig.secure ) { // It doesn't support through Unix sockets or Windows named pipes - var address = ( + let address = ( typeof process.serverConfig.port == "number" && listenAddress ? listenAddress : "localhost" @@ -2232,7 +2231,7 @@ function start(init) { if (address.indexOf(":") > -1) { address = "[" + address + "]"; } - var connection = http2.connect( + const connection = http2.connect( "http://" + address + ":" + diff --git a/src/middleware/nonStandardCodesAndHttpAuthentication.js b/src/middleware/nonStandardCodesAndHttpAuthentication.js index 4f5487a..164be7f 100644 --- a/src/middleware/nonStandardCodesAndHttpAuthentication.js +++ b/src/middleware/nonStandardCodesAndHttpAuthentication.js @@ -29,7 +29,7 @@ let passwordHashCacheIntervalId = -1; // Non-standard code object let nonStandardCodes = []; process.serverConfig.nonStandardCodes.forEach((nonStandardCodeRaw) => { - var newObject = {}; + let newObject = {}; Object.keys(nonStandardCodeRaw).forEach((nsKey) => { if (nsKey != "users") { newObject[nsKey] = nonStandardCodeRaw[nsKey]; @@ -77,7 +77,7 @@ module.exports = (req, res, logFacilities, config, next) => { ); if (nonStandardCodes[i].regex) { // Regex match - var createdRegex = createRegex(nonStandardCodes[i].regex, true); + const createdRegex = createRegex(nonStandardCodes[i].regex, true); isMatch = req.url.match(createdRegex) || hrefWithoutDuplicateSlashes.match(createdRegex); diff --git a/src/middleware/redirects.js b/src/middleware/redirects.js index d594f73..5e02caf 100644 --- a/src/middleware/redirects.js +++ b/src/middleware/redirects.js @@ -9,7 +9,7 @@ module.exports = (req, res, logFacilities, config, next) => { !config.disableNonEncryptedServer && !config.disableToHTTPSRedirect ) { - var hostx = req.headers.host; + const hostx = req.headers.host; if (hostx === undefined) { logFacilities.errmessage("Host header is missing."); res.error(400); @@ -22,7 +22,7 @@ module.exports = (req, res, logFacilities, config, next) => { return; } - var isPublicServer = !( + const isPublicServer = !( req.socket.realRemoteAddress ? req.socket.realRemoteAddress : req.socket.remoteAddress @@ -30,11 +30,11 @@ module.exports = (req, res, logFacilities, config, next) => { /^(?:localhost$|::1$|f[c-d][0-9a-f]{2}:|(?:::ffff:)?(?:(?:127|10)\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}|192\.168\.[0-9]{1,3}\.[0-9]{1,3}|172\.(?:1[6-9]|2[0-9]|3[0-1])\.[0-9]{1,3}\.[0-9]{1,3})$)/i, ); - var destinationPort = 0; + let destinationPort = 0; - var parsedHostx = hostx.match(/(\[[^\]]*\]|[^:]*)(?::([0-9]+))?/); - var hostname = parsedHostx[1]; - var hostPort = parsedHostx[2] ? parseInt(parsedHostx[2]) : 80; + const parsedHostx = hostx.match(/(\[[^\]]*\]|[^:]*)(?::([0-9]+))?/); + let hostname = parsedHostx[1]; + let hostPort = parsedHostx[2] ? parseInt(parsedHostx[2]) : 80; if (isNaN(hostPort)) hostPort = 80; if ( diff --git a/src/middleware/responseHeaders.js b/src/middleware/responseHeaders.js index 393c42a..db746eb 100644 --- a/src/middleware/responseHeaders.js +++ b/src/middleware/responseHeaders.js @@ -1,6 +1,6 @@ module.exports = (req, res, logFacilities, config, next) => { if (!req.isProxy) { - var hkh = config.getCustomHeaders(); + const hkh = config.getCustomHeaders(); Object.keys(hkh).forEach((hkS) => { try { res.setHeader(hkS, hkh[hkS]); diff --git a/src/middleware/rewriteURL.js b/src/middleware/rewriteURL.js index c4cce0f..a11ab2d 100644 --- a/src/middleware/rewriteURL.js +++ b/src/middleware/rewriteURL.js @@ -30,7 +30,7 @@ module.exports = (req, res, logFacilities, config, next) => { fs.stat( "." + decodeURIComponent(req.parsedURL.pathname), (err, stats) => { - var _fileState = 3; + let _fileState = 3; if (err) { _fileState = 3; } else if (stats.isDirectory()) { @@ -126,7 +126,7 @@ module.exports = (req, res, logFacilities, config, next) => { logFacilities.errmessage("Content blocked."); return; } else if (sHref != req.parsedURL.pathname) { - var rewrittenAgainURL = + const rewrittenAgainURL = sHref + (req.parsedURL.search ? req.parsedURL.search : "") + (req.parsedURL.hash ? req.parsedURL.hash : ""); diff --git a/src/middleware/staticFileServingAndDirectoryListings.js b/src/middleware/staticFileServingAndDirectoryListings.js index bea1530..d210359 100644 --- a/src/middleware/staticFileServingAndDirectoryListings.js +++ b/src/middleware/staticFileServingAndDirectoryListings.js @@ -34,7 +34,7 @@ module.exports = (req, res, logFacilities, config, next) => { let levelDownCount = 0; // Loop through the path components - for (var i = 0; i < pathComponents.length; i++) { + for (let i = 0; i < pathComponents.length; i++) { // If the component is "..", decrement the levelUpCount if (".." === pathComponents[i]) { levelUpCount--; @@ -313,7 +313,7 @@ module.exports = (req, res, logFacilities, config, next) => { // Helper function to check if compression is allowed for the file const canCompress = (path, list) => { let canCompress = true; - for (var i = 0; i < list.length; i++) { + for (let i = 0; i < list.length; i++) { if (createRegex(list[i], true).test(path)) { canCompress = false; break; @@ -437,7 +437,7 @@ module.exports = (req, res, logFacilities, config, next) => { }) .on("open", () => { try { - var resStream = {}; + let resStream = {}; if (useBrotli && isCompressable) { resStream = zlib.createBrotliCompress(); resStream.pipe(res); @@ -738,7 +738,7 @@ module.exports = (req, res, logFacilities, config, next) => { // Get stats for all files in the directory and generate the listing getStatsForAllFiles(list, readFrom, (filelist) => { let directoryListingRows = []; - for (var i = 0; i < filelist.length; i++) { + for (let i = 0; i < filelist.length; i++) { if (filelist[i].name[0] !== ".") { const estats = filelist[i].stats; const ename = filelist[i].name; diff --git a/src/utils/generateErrorStack.js b/src/utils/generateErrorStack.js index 8451a11..24f9af4 100644 --- a/src/utils/generateErrorStack.js +++ b/src/utils/generateErrorStack.js @@ -1,7 +1,7 @@ // Generate V8-style error stack from Error object. function generateErrorStack(errorObject) { // Split the error stack by newlines. - var errorStack = errorObject.stack ? errorObject.stack.split("\n") : []; + const errorStack = errorObject.stack ? errorObject.stack.split("\n") : []; // If the error stack starts with the error name, return the original stack (it is V8-style then). if ( @@ -13,7 +13,7 @@ function generateErrorStack(errorObject) { } // Create a new error stack with the error name and code (if available). - var newErrorStack = [ + let newErrorStack = [ errorObject.name + (errorObject.code ? ": " + errorObject.code : "") + (errorObject.message == "" ? "" : ": " + errorObject.message), @@ -23,12 +23,12 @@ function generateErrorStack(errorObject) { errorStack.forEach((errorStackLine) => { if (errorStackLine != "") { // Split the line into function and location parts (if available). - var errorFrame = errorStackLine.split("@"); - var location = ""; + let errorFrame = errorStackLine.split("@"); + let location = ""; if (errorFrame.length > 1 && errorFrame[0] == "global code") errorFrame.shift(); if (errorFrame.length > 1) location = errorFrame.pop(); - var func = errorFrame.join("@"); + const func = errorFrame.join("@"); // Build the new error stack entry with function and location information. newErrorStack.push( diff --git a/src/utils/getOS.js b/src/utils/getOS.js index 7f181eb..b64c7a5 100644 --- a/src/utils/getOS.js +++ b/src/utils/getOS.js @@ -1,12 +1,12 @@ const os = require("os"); function getOS() { - var osType = os.type(); - var platform = os.platform(); + const osType = os.type(); + const platform = os.platform(); if (platform == "android") { return "Android"; } else if (osType == "Windows_NT" || osType == "WindowsNT") { - var arch = os.arch(); + const arch = os.arch(); if (arch == "ia32") { return "Win32"; } else if (arch == "x64") { diff --git a/src/utils/ipBlockList.js b/src/utils/ipBlockList.js index 2d4fda7..cdeea64 100644 --- a/src/utils/ipBlockList.js +++ b/src/utils/ipBlockList.js @@ -2,7 +2,7 @@ function ipBlockList(rawBlockList) { // Initialize the instance with empty arrays if (rawBlockList === undefined) rawBlockList = []; - var instance = { + const instance = { raw: [], rawtoPreparedMap: [], prepared: [], diff --git a/src/utils/ipSubnetUtils.js b/src/utils/ipSubnetUtils.js index e2aeeeb..8a6cfcb 100644 --- a/src/utils/ipSubnetUtils.js +++ b/src/utils/ipSubnetUtils.js @@ -14,7 +14,7 @@ function calculateBroadcastIPv4FromCidr(ipWithCidr) { .split(".") .map((num, index) => { // Calculate resulting 8-bit - var power = Math.max(Math.min(mask - index * 8, 8), 0); + const power = Math.max(Math.min(mask - index * 8, 8), 0); return ( (parseInt(num) & ((Math.pow(2, power) - 1) << (8 - power))) | (Math.pow(2, 8 - power) - 1) @@ -39,7 +39,7 @@ function calculateNetworkIPv4FromCidr(ipWithCidr) { .split(".") .map((num, index) => { // Calculate resulting 8-bit - var power = Math.max(Math.min(mask - index * 8, 8), 0); + const power = Math.max(Math.min(mask - index * 8, 8), 0); return ( parseInt(num) & ((Math.pow(2, power) - 1) << (8 - power)) diff --git a/src/utils/serverconsole.js b/src/utils/serverconsole.js index 096ba0e..60c613e 100644 --- a/src/utils/serverconsole.js +++ b/src/utils/serverconsole.js @@ -78,7 +78,7 @@ function LOG(s) { } // Server console function -var serverconsole = { +const serverconsole = { climessage: (msg, reqId) => { if (msg.indexOf("\n") != -1) { msg.split("\n").forEach((nmsg) => {