Untitled conversation
- User
(async () => { const https = require('https'); const httpProxy = require('http-proxy'); const url = require('url'); const path = require('path'); const fs = require('fs'); const os = require('os'); const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const { EventEmitter } = require('events'); const axios = require('axios'); const geoip = require('geoip-lite'); const exec = require('child_process').exec; const { spawn } = require('child_process'); const dgram = require('dgram'); const basicAuth = require('express-basic-auth'); const osu = require('os-utils'); const { netstat } = require('node-os-utils'); const mem = require('node-os-utils').mem; const gradient = (await import('gradient-string')).default; // Create an Agent instance configured for keep-alive const keepAliveAgent = new https.Agent({ keepAlive: true, maxSockets: 100, maxFreeSockets: 10, }); axios.defaults.httpsAgent = keepAliveAgent; let logMessages = []; const originalLog = console.log; console.log = (...args) => { originalLog(...args); logMessages.push(args.join(' ')); }; const synFloodTracker = {}; const MAX_SYN_REQUESTS = 10; const SYN_BLOCK_TIME_MS = 60000; // Rate Limiting Configurations const rateLimit = {}; const MAX_REQUESTS_PER_MINUTE = 100; const BLOCK_TIME_MS = 60000; // DNS attack prevention configurations const dnsWhitelist = ['8.8.8.8', '1.1.1.1']; const MAX_DNS_REQUESTS_PER_MINUTE = 50; const dnsRateLimit = {}; // UDP Rate Limiting Configurations const udpRateLimit = {}; const MAX_UDP_REQUESTS_PER_MINUTE = 100; const UDP_BLOCK_TIME_MS = 60000; // Network Usage Limiting Configurations const networkUsage = {}; const MAX_BYTES_PER_MINUTE = 1024 * 1024; const NETWORK_BLOCK_TIME_MS = 60000; // Cloud Server IP Ranges const cloudServerIpRanges = ['35.', '52.', '169.', '198.', '199.', '200.', '216.', '47.']; // Allowed Countries for GeoIP const allowedCountries = ['ID', 'SG', 'PH']; const configApp = express(); const CONFIG_PORT = 6969; // Middleware configApp.set('view engine', 'ejs'); configApp.use(bodyParser.urlencoded({ extended: true })); configApp.use(express.static('public')); // Function to check and update DNS rate limits const isSuspiciousDNSRequest = (ip, requestUrl) => { if (!requestUrl.toLowerCase().includes('dns')) return false; if (!dnsWhitelist.includes(ip)) { const now = Date.now(); if (!dnsRateLimit[ip]) { dnsRateLimit[ip] = { count: 1, timestamp: now }; } else { const timePassed = now - dnsRateLimit[ip].timestamp; if (timePassed > BLOCK_TIME_MS) { dnsRateLimit[ip] = { count: 1, timestamp: now }; } else { dnsRateLimit[ip].count++; } if (dnsRateLimit[ip].count > MAX_DNS_REQUESTS_PER_MINUTE) { return true; } } } return false; }; // Function to check and update UDP rate limits const isUdpRateLimited = (ip) => { const now = Date.now(); if (!udpRateLimit[ip]) { udpRateLimit[ip] = { count: 1, timestamp: now }; return false; } else { const timePassed = now - udpRateLimit[ip].timestamp; if (timePassed > UDP_BLOCK_TIME_MS) { udpRateLimit[ip] = { count: 1, timestamp: now }; return false; } else { udpRateLimit[ip].count++; if (udpRateLimit[ip].count > MAX_UDP_REQUESTS_PER_MINUTE) { return true; } } } return false; }; // Function to check and update network usage const isNetworkUsageLimited = (ip, bytes) => { const now = Date.now(); if (!networkUsage[ip]) { networkUsage[ip] = { sent: bytes, received: bytes, timestamp: now }; return false; } else { const timePassed = now - networkUsage[ip].timestamp; if (timePassed > NETWORK_BLOCK_TIME_MS) { networkUsage[ip] = { sent: bytes, received: bytes, timestamp: now }; return false; } else { networkUsage[ip].sent += bytes; networkUsage[ip].received += bytes; if (networkUsage[ip].sent > MAX_BYTES_PER_MINUTE || networkUsage[ip].received > MAX_BYTES_PER_MINUTE) { return true; } } } return false; }; // Function to log blocked IPs const logBlockedIP = (ip, protocol = 'TCP') => { fs.appendFile('blocked_ips.log', `${new Date().toISOString()} - Blocked IP: ${ip} [${protocol}]\n`, (err) => { if (err) console.error(gradient.morning('Error logging blocked IP:'), err); }); }; // Function to normalize IP addresses const normalizeIp = (ip) => { if (ip.startsWith("::ffff:")) { return ip.substring(7); } if (ip === "::1") { return "127.0.0.1"; } return ip; }; // Function to check if IP is from cloud/server ranges const isCloudOrServerIp = (ip) => { return cloudServerIpRanges.some((range) => ip.startsWith(range)); }; // Helper function to check GeoIP blocking const isBlockedGeoIp = (ip) => { const geo = geoip.lookup(ip); if (geo && !allowedCountries.includes(geo.country)) { return true; } return false; }; const configPath = path.resolve(__dirname, './config/main.json'); const config = JSON.parse(fs.readFileSync(configPath, 'utf8')); // Fungsi untuk membaca konfigurasi const readConfig = () => { try { const data = fs.readFileSync(configPath, 'utf8'); return JSON.parse(data); } catch (err) { console.error(gradient.morning('Error membaca main.json:'), err); return {}; } }; // Fungsi untuk menulis konfigurasi const writeConfig = (config) => { try { fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8'); console.log(gradient.morning('Configuration updated.')); console.clear(); } catch (err) { console.error(gradient.morning('Error writing to Config:'), err); } }; // Middleware Autentikasi configApp.use('/config', basicAuth({ users: { [config.username]: config.password }, challenge: true, realm: 'Config Area' })); // Route untuk menampilkan form konfigurasi configApp.get('/config', (req, res) => { const config = readConfig(); res.render('config', { config }); }); // Route untuk memproses perubahan konfigurasi configApp.post('/config', (req, res) => { const { ip, port, loginurl, cdn, username, password } = req.body; const newConfig = { ip, port: parseInt(port), loginurl, cdn, username, password }; writeConfig(newConfig); res.redirect('/config'); }); configApp.get('/logs', (req, res) => { res.json({ logs: logMessages }); }); // Endpoint to gather system stats configApp.get('/stats', async (req, res) => { try { // Use os-utils or os for retrieving CPU and memory information const freeMemory = os.freemem(); const totalMemory = os.totalmem(); const usedMemory = totalMemory - freeMemory; const memoryUsagePercent = ((usedMemory) / totalMemory) * 100; osu.cpuUsage(async (cpuPercentage) => { const network = await netstat.inOut(); res.json({ memoryUsage: { free: freeMemory, total: totalMemory, usedPercent: memoryUsagePercent.toFixed(2), }, cpuUsage: (cpuPercentage * 100).toFixed(2), network: { inputMb: network.inputMb, outputMb: network.outputMb } }); }); } catch (error) { console.error('Error fetching system statistics:', error); res.json({ error: 'Unable to fetch system statistics' }); } }); configApp.post('/restart', (req, res) => { console.log('Restarting server...'); res.send('Server restarting...'); process.exit(1); }); const isSynFlood = (ip) => { const now = Date.now(); if (!synFloodTracker[ip]) { synFloodTracker[ip] = { count: 1, timestamp: now }; return false; } const timePassed = now - synFloodTracker[ip].timestamp; if (timePassed > SYN_BLOCK_TIME_MS) { synFloodTracker[ip] = { count: 1, timestamp: now }; return false; } else { synFloodTracker[ip].count++; if (synFloodTracker[ip].count > MAX_SYN_REQUESTS) { console.log(gradient.fruit(`SYN flood detected from IP: ${ip}`)); logBlockedIP(ip, 'SYN Flood'); return true; } } return false; }; // Start UI Server configApp.listen(CONFIG_PORT, () => { // console.log(gradient.cristal('ADMIN DASHBOARD IS ONLINE')); }); // Start Server Function const startServer = async () => { const proxy = httpProxy.createProxyServer({}); const pk = fs.readFileSync(path.join(__dirname, 'server.key')); const pc = fs.readFileSync(path.join(__dirname, 'server.crt')); const optss = { key: pk, cert: pc }; const trustedIPs = ['127.0.0.1']; const port = process.argv[2] || 443; EventEmitter.defaultMaxListeners = 100; const packet = `server|${config.ip}\nport|${config.port}\ntype|1\n#maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute.\n\n\nloginurl|${config.loginurl}\nbeta_server|127.0.0.1\nbeta_port|17091\nbeta_type|1\nbeta2_server|127.0.0.1\nbeta2_port|17099\nbeta2_type|1\nmeta|${Math.floor(Date.now() / 1000)}\nRTENDMARKERBS1001`; const server = https.createServer(optss, function (req, res) { let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; const normalizedIp = normalizeIp(ip); const hostHeader = req.headers.host; // Set keepAliveTimeout, which sets how long a connection should remain open in milliseconds. server.keepAliveTimeout = 30 * 1000; // Keep alive for 60 seconds // Set the headers timeout slightly longer than keepAliveTimeout to accommodate requests that arrive just before the keep alive timeout server.headersTimeout = 30 * 1000; // 65 seconds //console.log(gradient.passion(`[DEVELOPER MODE]`, req.headers['user-agent'])); console.log(gradient.passion(`[REQUEST] IP: ${normalizedIp}`)); if (isSynFlood(ip)) { console.log(gradient.fruit(`SYN flood detected from IP: ${normalizedIp}`)); logBlockedIP(normalizedIp, 'SYN Flood'); // Use the underlying socket to destroy the connection req.socket.end(); req.socket.destroy(); return; } // Rate Limiting Logic if (!rateLimit[normalizedIp]) { rateLimit[normalizedIp] = { count: 1, timestamp: Date.now() }; } else { const currentTime = Date.now(); const timePassed = currentTime - rateLimit[normalizedIp].timestamp; // Reset the count if more than 1 minute has passed if (timePassed > BLOCK_TIME_MS) { rateLimit[normalizedIp] = { count: 1, timestamp: currentTime }; } else { rateLimit[normalizedIp].count++; } // Check if the limit is reached if (rateLimit[normalizedIp].count > MAX_REQUESTS_PER_MINUTE) { console.log(gradient.summer(`Rate limit exceeded for IP: ${normalizedIp}`)); logBlockedIP(normalizedIp, 'TCP'); res.statusCode = 429; // Too Many Requests res.end('Too many requests. Your connection is being throttled.'); return; } } // DNS attack protection if (isSuspiciousDNSRequest(normalizedIp, req.url)) { console.log(gradient.summer(`DNS DDoS detected from IP: ${normalizedIp}`)); logBlockedIP(normalizedIp, 'TCP-DNS'); res.statusCode = 403; // Forbidden res.end('Forbidden: DNS DDoS attack detected.'); return; } // Network Usage Limiting for TCP const requestBytes = Buffer.byteLength(req.url); // Approximate if (isNetworkUsageLimited(normalizedIp, requestBytes)) { console.log(gradient.summer(`Network usage limit exceeded for IP: ${normalizedIp} (TCP)`)); logBlockedIP(normalizedIp, 'TCP-NETWORK'); res.statusCode = 429; // Too Many Requests res.end('Too many requests. Your connection is being throttled.'); return; } // Check for cloud or server IP range if (!trustedIPs.includes(normalizedIp) && isCloudOrServerIp(normalizedIp)) { console.log(gradient.summer(`Blocking cloud/server IP: ${normalizedIp}`)); logBlockedIP(normalizedIp, 'TCP-Cloud'); res.statusCode = 403; res.end('Forbidden: Access from cloud/server IP is blocked.'); return; } // Check for GeoIP block if (isBlockedGeoIp(normalizedIp)) { console.log(gradient.summer(`Blocking access from IP: ${normalizedIp} (GeoIP Block)`)); logBlockedIP(normalizedIp, 'TCP-GeoIP'); res.statusCode = 403; res.end('Forbidden: Access from your location is blocked.'); return; } const parsedUrl = url.parse(req.url); const pathname = `.${parsedUrl.pathname}`; const ext = path.parse(pathname).ext; console.log(gradient.atlas(`Connection Request from: ${normalizedIp} URL: ${req.url} Method: ${req.method}`)); const map = { '.ico': 'image/x-icon', '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.css': 'text/css', '.png': 'image/png', '.jpg': 'image/jpeg', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.doc': 'application/msword' }; const allowedUserAgents = [ 'UbiServices_SDK_2022.Release.9_PC64_ansi_static', 'UbiServices_SDK_2022.Release.9_PC32_ansi_static', 'UbiServices_SDK_2022.Release.9_ANDROID64_static', 'UbiServices_SDK_2022.Release.9_ANDROID32_static', 'UbiServices_SDK_2022.Release.9_IOS64', 'UbiServices_SDK_2022.Release.9_IOS32', 'UbiServices_SDK_2022.Release.9_MAC64', 'UbiServices_SDK_2022.Release.9_MAC32', ]; const userAgent = req.headers['user-agent']; // Handle /growtopia/server_data.php - Only POST and allowed User-Agents if (req.url === "/growtopia/server_data.php") { if (req.method !== 'POST' || hostHeader !== 'www.growtopia1.com' || !allowedUserAgents.includes(userAgent)) { console.log(gradient.summer(`Mata mata : ${req.url}`)); res.statusCode = 403; res.end(` server|${normalizedIp} port|${Math.floor(Date.now() / 69)} type|1 #maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute. loginurl|http-king.com beta_server|${normalizedIp} beta_port|${Math.floor(Date.now() / 69)} beta_type|1 beta2_server|${normalizedIp} beta2_port|${Math.floor(Date.now() / 69)} beta2_type|1 meta|69-SCP-PROTECTION RTENDMARKERBS1001 `); return; } res.write(packet, function (err) { if (err) console.log(gradient.summer(err)); }); res.end(); } // Handle /cache and /0098 - Only GET and allowed User-Agents else if (req.url.indexOf("/cache") !== -1 || req.url.indexOf("/0098") !== -1) { if (req.method !== 'GET' || !allowedUserAgents.includes(userAgent)) { console.log(gradient.summer(`Blocked: Invalid method or User-Agent for ${req.url}`)); res.statusCode = 403; res.end('Hello world'); return; } console.log(gradient.atlas(`[CACHE-SPEED] Connection from: ${normalizedIp}\n Downloading assets: ${req.url}`)); fs.exists(pathname, function (exist) { if (!exist) { res.statusCode = 301; res.writeHead(301, { Location: `https://ubistatic-a.akamaihd.net/${config.cdn}${req.url}` }).end(); return; } fs.readFile(pathname, function (err, data) { if (err) { res.statusCode = 404; res.end(`error`); } else { res.setHeader('Content-type', map[ext] || 'text/plain'); res.end(data); } }); }); } // Block all other requests else { console.log(gradient.summer(`🛡 [PROTECTION] Blocked request: ${req.method} ${req.url} from IP: ${normalizedIp}`)); logBlockedIP(normalizedIp, 'TCP-Other'); res.statusCode = 403; res.end('Hello world'); } }); server.listen(port, () => { console.log(gradient.cristal(`Server is running on port ${port}`)); }); // -------------------- UDP Server Setup -------------------- const udpServer = dgram.createSocket('udp4'); const UDP_PORT = 53; udpServer.on('error', (err) => { console.error(`UDP server error:\n${err.stack}`); udpServer.close(); }); udpServer.on('message', (msg, rinfo) => { const ip = rinfo.address; const normalizedIp = normalizeIp(ip); console.log(gradient.fruit(`UDP request from IP: ${normalizedIp}, Port: ${rinfo.port}`)); // Rate Limiting if (isUdpRateLimited(normalizedIp)) { console.log(gradient.summer(`UDP Rate limit exceeded for IP: ${normalizedIp}`)); logBlockedIP(normalizedIp, 'UDP'); return; } // GeoIP Blocking if (isBlockedGeoIp(normalizedIp)) { console.log(gradient.summer(`Blocking UDP access from IP: ${normalizedIp} (GeoIP Block)`)); logBlockedIP(normalizedIp, 'UDP-GeoIP'); return; } // Network Usage Limiting for UDP const messageBytes = msg.length; if (isNetworkUsageLimited(normalizedIp, messageBytes)) { console.log(gradient.summer(`Network usage limit exceeded for IP: ${normalizedIp} (UDP)`)); logBlockedIP(normalizedIp, 'UDP-NETWORK'); return; } // Implement your DNS handling logic here const externalDns = '8.8.8.8'; const externalDnsPort = 53; const externalClient = dgram.createSocket('udp4'); externalClient.send(msg, 0, msg.length, externalDnsPort, externalDns, (error) => { if (error) { console.error(`Error forwarding UDP request: ${error}`); externalClient.close(); } }); externalClient.on('message', (response) => { udpServer.send(response, 0, response.length, rinfo.port, rinfo.address, (err) => { if (err) { console.error(`Error sending UDP response: ${err}`); } externalClient.close(); }); }); // Optional: Implement timeouts to prevent hanging externalClient.on('error', (err) => { console.error(`External DNS client error: ${err}`); externalClient.close(); }); // Set a timeout for the external DNS response externalClient.setTimeout(5000, () => { console.error(`External DNS request timed out for IP: ${normalizedIp}`); externalClient.close(); }); }); udpServer.on('listening', () => { const address = udpServer.address(); console.log(gradient.morning(`UDP Server listening on ${address.address}:${address.port}`)); }); udpServer.bind(UDP_PORT); const shutdown = () => { console.log('Shutting down the server...'); // Stop the server from accepting new connections server.close(() => { console.log('HTTP server closed.'); // Close the UDP server udpServer.close(() => { console.log('UDP server closed.'); // Exit the process process.exit(0); }); }); // Ensure shutdown if connections remain setTimeout(() => { console.error('Forced shutdown due to open connections.'); process.exit(1); // exit with error code if connections remain }, 5000).unref(); }; configApp.post('/shutdown', (req, res) => { res.send('Server is shutting down...'); shutdown(); }); // Capture abort signals process.on('SIGINT', shutdown); process.on('SIGTERM', shutdown); console.log(''); console.log(gradient.vice('========================================================')); console.log(gradient.vice(`- CONFIGURATION LOADS : `)); console.log(gradient.vice(`[🎮] Login URL : ${config.loginurl}`)); console.log(gradient.vice(`[🔰] HTTP Port ${port}`)); console.log(gradient.vice(`[@] ANTI-SCAN SERVER DATA PHP STATUS : ENABLED [PENTEST-SECURITY]`)); console.log(gradient.vice(`[@] OPERATION SYSTEM : WINDOWS`)); console.log(gradient.vice(`[@] HTTP KING VERSION : 4.0.0`)); console.log(gradient.cristal(`[🥇] SUBSCRIPTION : PREMIUM`)); console.log(gradient.cristal(`[✅] LAST HTTP UPDATE : 21/10/2024`)); console.log(gradient.passion(`[💻] ADMIN DASHBOARD : http://localhost:${CONFIG_PORT}/config`)); console.log(gradient.vice('========================================================')); console.log(''); console.log(gradient.pastel(` ::: ::: ::::::::::: :::: ::: :::::::: ::: ::: :::::::: :::::::: :+: :+: :+: :+:+: :+: :+: :+: :+: :+: :+: :+: :+: :+: +:+ +:+ +:+ :+:+:+ +:+ +:+ +:+ +:+ +:+ +:+ +#++:++ +#+ +#+ +:+ +#+ :#: +#+ +:+ +#++: +#++: #+ +#+ +#+ +#+ +#+#+# +#+ +#+# +#+ +#+ +#+ +#+ #+# #+# #+# #+# #+#+# #+# #+# #+#+# #+# #+# #+# #+# ### ### ########### ### #### ######## ### ######## ######## `)); } startServer(); })();Can you add auto install not installed package module
- Assistant
To add functionality for automatically installing missing Node.js packages, you can modify your function to check for required packages and install any that are missing. Here's how you can integrate this feature into your script:
// Function to require modules and install if not present const requireWithInstall = async (packageName) => { try { return require(packageName); } catch (err) { if (err.code === 'MODULE_NOT_FOUND') { console.log(`Package ${packageName} not found. Installing...`); await new Promise((resolve, reject) => { require('child_process').exec(`npm install ${packageName}`, (error, stdout, stderr) => { if (error) { console.error(`Error installing ${packageName}: ${stderr}`); reject(error); } else { console.log(`Package ${packageName} installed successfully.`); resolve(); } }); }); return require(packageName); } else { throw err; } } }; (async () => { const https = await requireWithInstall('https'); const httpProxy = await requireWithInstall('http-proxy'); const url = await requireWithInstall('url'); const path = await requireWithInstall('path'); const fs = await requireWithInstall('fs'); const os = await requireWithInstall('os'); const express = await requireWithInstall('express'); const bodyParser = await requireWithInstall('body-parser'); const cors = await requireWithInstall('cors'); const { EventEmitter } = await requireWithInstall('events'); const axios = await requireWithInstall('axios'); const geoip = await requireWithInstall('geoip-lite'); const { exec } = await requireWithInstall('child_process'); const { spawn } = await requireWithInstall('child_process'); const dgram = await requireWithInstall('dgram'); const basicAuth = await requireWithInstall('express-basic-auth'); const osu = await requireWithInstall('os-utils'); const { netstat } = await requireWithInstall('node-os-utils'); const gradient = (await requireWithInstall('gradient-string')).default; // The rest of your code remains the same...Explanation:
-
Function
requireWithInstall: This function attempts torequirea module. If the module is not found (MODULE_NOT_FOUND), it useschild_processto executenpm install <module>. After installation, it requires the module again to proceed as normal. -
Asynchronous Execution: Since installing packages is an asynchronous operation,
requireWithInstallreturns a promise that resolves when installation is complete. This ensures that the script waits for the installation to finish before proceeding. -
Error Handling: In case there is an error other than
MODULE_NOT_FOUND, the function will throw the error, allowing you to handle it accordingly. Additionally, it logs any errors that occur during installation.
Now, whenever you run this script, it will automatically install any missing packages, making it user-friendly and more robust for environments where dependencies need to be installed on the fly.
-
- User
nope, still it ask me to install manually
- Assistant
To make sure that missing npm packages are automatically installed without manually running
npm install, we can modify the script to attempt to import required modules, and if not available, automatically trigger npm to install the missing package. Let's integrate this process smoothly:- Using
child_processto run a shell command to install the missing package. - Include package installation steps before requiring modules.
Here's a code snippet that does this:
const execSync = require('child_process').execSync; // Function to require modules and install if not present async function requireWithInstall(packageName) { try { return require(packageName); } catch (err) { if (err.code === 'MODULE_NOT_FOUND') { console.log(`Package "${packageName}" not found. Installing...`); try { // Install the package execSync(`npm install ${packageName}`, { stdio: 'inherit' }); console.log(`Package "${packageName}" installed successfully.`); // Try to require again after installation return require(packageName); } catch (installErr) { console.error(`Failed to install package "${packageName}".`, installErr); throw installErr; } } else { throw err; } } } (async () => { const https = await requireWithInstall('https'); const httpProxy = await requireWithInstall('http-proxy'); const url = await requireWithInstall('url'); const path = await requireWithInstall('path'); const fs = await requireWithInstall('fs'); const os = await requireWithInstall('os'); const express = await requireWithInstall('express'); const bodyParser = await requireWithInstall('body-parser'); const cors = await requireWithInstall('cors'); const { EventEmitter } = await requireWithInstall('events'); const axios = await requireWithInstall('axios'); const geoip = await requireWithInstall('geoip-lite'); const { exec } = await requireWithInstall('child_process'); const { spawn } = await requireWithInstall('child_process'); const dgram = await requireWithInstall('dgram'); const basicAuth = await requireWithInstall('express-basic-auth'); const osu = await requireWithInstall('os-utils'); const { netstat } = await requireWithInstall('node-os-utils'); const mem = (await requireWithInstall('node-os-utils')).mem; const gradient = (await import('gradient-string')).default; // The rest of your code remains the same... })();Explanation:
-
execSyncUsage: This script utilizes Node.js'schild_process.execSyncmethod to run thenpm installcommand right within the script. This is a synchronous operation and will block until it completes, ensuring that the package is installed before proceeding to require it again. -
Installation Check: The
requireWithInstallfunction checks for the presence of a module and executesnpm install <module>if the module isn't found. It logs both the start and success (or failure) of installation attempts. -
Standard I/O for Logging: Using
stdio: 'inherit'ensures that the npm logs are printed directly to the process' standard output and error, making it clear what is happening during the installation process.
This method allows the script to handle its dependencies dynamically, simplifying deployment in environments without pre-installed npm packages. Ensure this script is executed from a directory with a
package.jsonfile to prevent npm from creating a new defaultpackage.json. - Using
- User
node:internal/modules/cjs/loader:1225 const err = new Error(message); ^
Error: Cannot find module 'http-proxy' Require stack:
- C:\Users\head\Desktop\AVIATUM LE NORA\start.js at Module._resolveFilename (node:internal/modules/cjs/loader:1225:15) at Module._load (node:internal/modules/cjs/loader:1051:27) at Module.require (node:internal/modules/cjs/loader:1311:19) at require (node:internal/modules/helpers:179:18) at C:\Users\head\Desktop\AVIATUM LE NORA\start.js:27:21 at Object. (C:\Users\head\Desktop\AVIATUM LE NORA\start.js:665:5) at Module._compile (node:internal/modules/cjs/loader:1469:14) at Module._extensions..js (node:internal/modules/cjs/loader:1548:10) at Module.load (node:internal/modules/cjs/loader:1288:32) at Module._load (node:internal/modules/cjs/loader:1104:12) { code: 'MODULE_NOT_FOUND', requireStack: [ 'C:\Users\head\Desktop\AVIATUM LE NORA\start.js' ] }
- Assistant
It seems like the automatic installation of a missing module isn't working as intended. Let's debug this and adjust the code to ensure it correctly installs missing packages. Here's an updated approach:
- Ensure the fallback package installation is running in case of a module not found error.
- Check the environment and directories to ensure npm commands are properly executing.
Here's the revised code snippet:
const { execSync } = require('child_process'); // Function to require modules and install if not present async function requireWithInstall(packageName) { try { return require(packageName); } catch (err) { if (err.code === 'MODULE_NOT_FOUND') { console.log(`Package "${packageName}" not found. Installing...`); try { // Install the package execSync(`npm install ${packageName}`, { stdio: 'inherit' }); console.log(`Package "${packageName}" installed successfully.`); // Try to require again after installation return require(packageName); } catch (installErr) { console.error(`Failed to install package "${packageName}".`, installErr); throw installErr; } } else { throw err; } } } (async () => { const https = await requireWithInstall('https'); const httpProxy = await requireWithInstall('http-proxy'); const url = await requireWithInstall('url'); const path = await requireWithInstall('path'); const fs = await requireWithInstall('fs'); const os = await requireWithInstall('os'); const express = await requireWithInstall('express'); const bodyParser = await requireWithInstall('body-parser'); const cors = await requireWithInstall('cors'); const { EventEmitter } = await requireWithInstall('events'); const axios = await requireWithInstall('axios'); const geoip = await requireWithInstall('geoip-lite'); const { exec } = await requireWithInstall('child_process'); const { spawn } = require('child_process'); // Direct require since it's built-in const dgram = require('dgram'); // Direct require since it's built-in const basicAuth = await requireWithInstall('express-basic-auth'); const osu = await requireWithInstall('os-utils'); const nodeOsUtils = await requireWithInstall('node-os-utils'); const { netstat } = nodeOsUtils; const { mem } = nodeOsUtils; const gradient = (await requireWithInstall('gradient-string')).default; // Your existing code follows... })();Key Details:
-
Built-in Modules: For built-in Node.js modules like
child_processanddgram, you don't need to install them; you can require them directly as they already come with Node.js. -
Error Handling: The
requireWithInstallfunction should catch theMODULE_NOT_FOUNDerror and attempt to install the package usingnpm install. -
Correct Execution Directory: Ensure that you're running the script from a directory with a valid
package.jsonto avoid npm issues. -
Asynchronous Execution: The
execSyncmethod is used to synchronously install the package, ensuring the script doesn't proceed until installation is complete.
This should help handle automatic package installation in a way that best fits your development setup. Make sure Node.js and npm are properly configured on your machine to execute shell commands successfully.