const synFloodTracker = {};
const MAX_SYN_REQUESTS = 10; // Max allowed per minute
const SYN_BLOCK_TIME_MS = 60000; // Block time if SYN flood detected
// Rate Limiting Configurations
const rateLimit = {};
const MAX_REQUESTS_PER_MINUTE = 100; // Set your limit here (100)
const BLOCK_TIME_MS = 60000; // Time to block the IP (1 minute) (60000)
// DNS attack prevention configurations
const dnsWhitelist = ['8.8.8.8', '1.1.1.1']; // Trusted DNS resolvers (Google DNS and Cloudflare DNS)
const MAX_DNS_REQUESTS_PER_MINUTE = 50; // Limit DNS-related requests
const dnsRateLimit = {};
// 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;
};
configApp.post('/restart', (req, res) => {
console.log('Received request to restart the HTTP server...');
// Send response before restarting
res.send('Restarting server...');
// Spawn a new process and re-run the script (server.js)
spawn(process.argv[0], process.argv.slice(1), {
detached: true,
stdio: 'inherit'
});
// Exit the current process
process.exit();
});
configApp.post('/shutdown', (req, res) => {
console.log('Received request to shutdown the HTTP server...');
// Send response before restarting
res.send('Server is shutting down...');
// Exit the current process
process.exit(0);
});
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(chalk.red(SYN flood detected from IP: ${ip}));
logBlockedIP(ip, 'SYN Flood');
return true;
}
}
return false;
};
// Start UI Server
configApp.listen(CONFIG_PORT, () => {
console.log(chalk.blue(Admin dashboard is running on http://localhost:${CONFIG_PORT}/config));
});
// 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;
console.log(chalk.green([DEVELOPER MODE], req.headers['user-agent']));
console.log(chalk.green(Request received from IP: ${normalizedIp}));
code
// Handle /growtopia/server_data.php - Only POST and allowed User-Agents
if (req.url === "/growtopia/server_data.php") {
if (req.method !== 'POST' || hostHeader !== 'www.growtopia2.com') {
console.log(chalk.red(Mata mata : ${req.url}));
res.statusCode = 403;
res.end(`
server|normalizedIpport∣{Math.floor(Date.now() / 69)}
type|1
#maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute.
server.listen(port, () => {
console.log(chalk.green(Server is running on port ${port}));
});
// -------------------- UDP Server Setup --------------------
const udpServer = dgram.createSocket('udp4');
const UDP_PORT = 53; // DNS typically uses 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(chalk.yellow(UDP request from IP: ${normalizedIp}, Port: ${rinfo.port}));
code
// Rate Limiting
if (isUdpRateLimited(normalizedIp)) {
console.log(chalk.red(`UDP Rate limit exceeded for IP: ${normalizedIp}`));
logBlockedIP(normalizedIp, 'UDP');
return; // Drop the packet silently or send a response indicating rate limiting
}
// GeoIP Blocking
if (isBlockedGeoIp(normalizedIp)) {
console.log(chalk.red(`Blocking UDP access from IP: ${normalizedIp} (GeoIP Block)`));
logBlockedIP(normalizedIp, 'UDP-GeoIP');
return; // Drop the packet silently or send a forbidden response
}
// Network Usage Limiting for UDP
const messageBytes = msg.length;
if (isNetworkUsageLimited(normalizedIp, messageBytes)) {
console.log(chalk.red(`Network usage limit exceeded for IP: ${normalizedIp} (UDP)`));
logBlockedIP(normalizedIp, 'UDP-NETWORK');
return; // Drop the packet
}
// Implement your DNS handling logic here
// For example, respond with a simple DNS response or forward the request to a legitimate DNS server
// Example: Forward the DNS request to an external DNS server (e.g., Google DNS)
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, () => { // 5 seconds timeout
console.error(`External DNS request timed out for IP: ${normalizedIp}`);
externalClient.close();
});
});
udpServer.on('listening', () => {
const address = udpServer.address();
console.log(chalk.green(UDP Server listening on ${address.address}:${address.port}));
});
udpServer.bind(UDP_PORT);
console.log('')
console.log(chalk.magenta('========================================================'));
console.log(chalk.magenta(- CONFIGURATION LOADS : ));
console.log(chalk.magenta([@] Login URL : ${config.loginurl}));
console.log(chalk.magenta([@] HTTP Port ${port}));
console.log(chalk.magenta([@] ANTI-HOSTCHECK ${port}));
console.log(chalk.magenta([@] ANTI-SCAN SERVER DATA PHP STATUS : ENABLED [PENTEST-SECURITY]));
console.log(chalk.magenta([@] OPERATION SYSTEM : WINDOWS));
console.log(chalk.magenta([@] HTTP KING VERSION : 3.3.8));
console.log(chalk.greenBright([@] SUBSCRIPTION : VIP-SUPER));
console.log(chalk.greenBright([@] LAST HTTP UPDATE : 6/10/2024));
console.log(chalk.magenta('========================================================'));
console.log('')
console.log(chalk.green(`
To fix the restart and shutdown functionality of an Express application using spawn to rerun the script or process.exit(), you'll need to make sure the process communicates appropriately, since Express handles HTTP requests synchronously. Here’s how you can fix and implement these functionalities:
1. Fixing the Restart Function:
When you restart a server using spawn, the child process needs to be detached properly. The handling should ensure that the exiting process does not close the server's input/output, which can happen if not handled carefully in some environments.
2. Fixing the Shutdown Function:
When shutting down the server, allow the HTTP server to gracefully complete any pending requests before the process exits.
Code Implementation:
javascript
User
the problem is, everytime i click the button it always says [nodemon] clean exit - waiting for changes before restart, bruh please do automatic
Assistant
The issue you're encountering with nodemon is that it watches for file changes and automatically restarts the application. This behavior is typically useful during development but can interfere with custom restart mechanisms like the one you implemented using spawn.
Here's a way to handle application restarts and shutdowns without conflicting with nodemon:
Steps to Implement Automatic Restart and Shutdown:
Using a Process Monitor
For production environments, it's better to use a process manager like PM2 which can handle automatic restarts more gracefully. PM2 will keep your application running, handle logging, and can restart the application upon crashes or in response to commands.
Adjusting the Code for Production Use
If you intend to continue development with nodemon, consider handling restarts differently. For production, PM2 or systemd services should be preferred.
Instructions with PM2:
Install PM2 globally:
bash
npm install -g pm2
Start your application using PM2:
bash
pm2 start server.js --name="myapp"
Update your restart/shutdown routes:
You won't need commands that mess with the process directly using PM2. Instead, you can manage it through PM2 commands. However, here's how you can still design them:
javascript
const exec = require('child_process').exec;
// ...
configApp.post('/restart', (req, res) => {
console.log('Received request to restart the HTTP server...');
res.send('Restarting server...');
To effectively handle automatic restarts and shutdowns in a Node.js application, especially in a production-like environment, it's recommended to use a process manager like PM2. This approach avoids conflicts with tools like nodemon, which are typically used during development phases for live reloading on code changes.
Moving to PM2 for Application Management
Install PM2 Globally:
First, you'll want to install PM2 on your system to manage your Node.js application lifecycle.
bash
npm install -g pm2
Start Your Application Using PM2:
Instead of using node or nodemon, you'll start your application with PM2, which will handle restarts and monitoring.
bash
pm2 start server.js --name="myapp"
Modify Your Application for Restart and Shutdown Commands Using PM2:
You can use Node.js's exec from the child_process module to invoke PM2 commands through HTTP endpoints:
javascript
User
no pm2 is not good
Assistant
If PM2 doesn't suit your needs and you're looking to implement a custom restart and shutdown mechanism within your Node.js application without the constraints of a process manager, the approach will focus on handling restarts and shutdowns directly with your application code. Here's a way you can do this:
Direct Restart and Shutdown in Node.js
When handling restarts and shutdowns without a process manager, you'll need to be aware that the current script must handle its own lifecycle. Here’s a solution using Node’s spawn function to restart the application:
Implementation
javascript
const { spawn } = require('child_process');
const express = require('express');
const bodyParser = require('body-parser');
const basicAuth = require('express-basic-auth');
const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
const configApp = express();
const CONFIG_PORT = 6969;
const configPath = path.resolve(__dirname, './config/main.json');
let config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
// Middleware setup
configApp.use(bodyParser.urlencoded({ extended: true }));
// Secure access using basic auth
configApp.use('/config', basicAuth({
users: { [config.username]: config.password },
challenge: true,
realm: 'Config Area'
}));
// Render configuration form
configApp.get('/config', (req, res) => {
config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
res.render('config', { config });
});
// Endpoint to restart the application
configApp.post('/restart', (req, res) => {
console.log('Received request to restart the HTTP server...');
res.send('Restarting server...');
// Detach and start a new instance of the script
const child = spawn(process.argv[0], process.argv.slice(1), {
detached: true,
stdio: 'ignore'
});
// Detach the child process to keep it running independently
child.unref();
// Exit the current application process
process.exit();
});
// Endpoint to shutdown the application
configApp.post('/shutdown', (req, res) => {
console.log('Received request to shutdown the HTTP server...');
res.send('Server is shutting down...');
process.exit(0);
});
// Start the configuration UI server
configApp.listen(CONFIG_PORT, () => {
console.log(chalk.blue(`Admin dashboard is running on http://localhost:${CONFIG_PORT}/config`));
});
// Your main server logic goes here...
User
im using nodemon, and i got this error [nodemon] clean exit - waiting for changes before restart please fix it asap
Assistant
The message [nodemon] clean exit - waiting for changes before restart indicates that nodemon is waiting for file changes to restart your application. This typically happens because nodemon is designed to watch the file system for changes and restart the application automatically in a development environment.
However, when you manually handle restarts by spawning a new process and exiting the current process, nodemon might interpret this as a clean exit without any changes that would trigger an automatic restart.
Here is how you can adjust your setup to effectively use nodemon for automatic restarts during development, while managing manual restarts within your program:
Steps to Fix the Issue
Ensure nodemon is correctly installed and configured:
First, make sure you have nodemon installed globally or as a dev dependency:
sh
npm install -g nodemon
Or for a local project:
sh
npm install --save-dev nodemon
Update your nodemon.json:
If you have a nodemon.json configuration file, make sure it is configured to watch the necessary files and ignore system files or directories that should not trigger a restart.
Here's a basic example:
json
{
"watch": ["src/", "config/"], // Specify directories to watch
"ext": "js,json", // File extensions to watch
"ignore": ["node_modules/**"]
}
Handle Restarts with Explicit Signals:
Modify your restart logic so that when you are using nodemon, you can send a signal to nodemon to trigger the restart, rather than manually spawning processes.
Here's how you can adjust your code using fs to trigger file changes:
javascript
User
still the same
Assistant
Let's refine our approach for handling restarts within a Node.js application when using nodemon. To ensure that nodemon successfully restarts the application based on internal triggers without relying on an external process manager, we need to use a different strategy that aligns better with nodemon's behavior.
Strategy to Trigger Restarts with nodemon
To achieve this, we can use a different mechanism to trigger nodemon to restart the application forcibly. Since nodemon watches for file changes, we can make it restart by programmatically touching a file that nodemon is watching.
Here's a reliable way to implement this approach:
Ensure nodemon watches the right files: Make sure nodemon is set to watch files that you can easily programmatically edit to force a restart.
Modify the application logic: Use a simple technique to update a file that nodemon will react to, forcing the restart.
Implementation
javascript
const express = require('express');
const bodyParser = require('body-parser');
const basicAuth = require('express-basic-auth');
const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
const configApp = express();
const CONFIG_PORT = 6969;
const configPath = path.resolve(__dirname, './config/main.json');
let config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
// Middleware setup
configApp.use(bodyParser.urlencoded({ extended: true }));
// Secure configuration access using basic auth
configApp.use('/config', basicAuth({
users: { [config.username]: config.password },
challenge: true,
realm: 'Config Area'
}));
// Render configuration form
configApp.get('/config', (req, res) => {
config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
res.render('config', { config });
});
// Endpoint to trigger a restart
configApp.post('/restart', (req, res) => {
console.log('Received request to restart the HTTP server...');
res.send('Restarting server...');
// Update restart file's timestamp to trigger nodemon restart
const restartFile = path.resolve(__dirname, './restart.txt');
fs.writeFileSync(restartFile, `Restart triggered at ${new Date()}`);
});
// Shutdown endpoint
configApp.post('/shutdown', (req, res) => {
console.log('Received request to shutdown the HTTP server...');
res.send('Server is shutting down...');
process.exit(0);
});
// Start configuration UI server
configApp.listen(CONFIG_PORT, () => {
console.log(chalk.blue(`Admin dashboard is running on http://localhost:${CONFIG_PORT}/config`));
});
// Add the file (restart.txt) to be watched by nodemon for changes.
// Your main server logic goes here...
User
give me the /restart
Assistant
Certainly! Below is a specific implementation of just the /restart endpoint, which you can use with nodemon to trigger an application restart by touching a file that nodemon watches. This approach leverages nodemon's file watching capabilities to automatically restart the application:
/restart Endpoint Implementation
Here’s the code for the /restart endpoint:
javascript
const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
const PORT = 3000; // You can adjust the port as needed
// Endpoint to trigger a restart
app.post('/restart', (req, res) => {
console.log('Received request to restart the HTTP server...');
res.send('Restarting server...');
// Update the timestamp of the restart.txt file to trigger nodemon
const restartFile = path.resolve(__dirname, './restart.txt');
// Write current date-time to ensure a change is registered
fs.writeFileSync(restartFile, `Restart triggered at ${new Date()}`, (err) => {
if (err) {
console.error('Error writing to restart file:', err);
}
});
});
// Start the application
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
How It Works
Express Application: This snippet sets up a minimal Express server with a single POST endpoint /restart.
Writing to restart.txt: When this endpoint is accessed, the server writes a timestamp to a file named restart.txt within your project directory.
File Watch with nodemon: Nodemon is configured to watch the restart.txt file for changes. Any change to this file's content or timestamp triggers nodemon to restart the application.
Configuring nodemon
Ensure that nodemon is set up to watch the restart.txt file. Here’s how to do it:
User
make sure its real restart the nodejs
Assistant
To ensure that the Node.js application truly restarts with nodemon when you hit the /restart endpoint, you'll need to configure the application and nodemon carefully. I'll show you how to set up an Express server where a POST request to /restart will lead to a genuine restart of the application by utilizing nodemon's file-watching capability.
Complete Example
Here's a working example:
javascript
// app.js
const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
const PORT = 3000; // Use any port you prefer
// Endpoint to trigger a restart
app.post('/restart', (req, res) => {
console.log('Received request to restart the server...');
// Send a response before attempting to restart
res.send('Restarting server...');
// Action to trigger a restart: updating a watched file
const restartFilePath = path.join(__dirname, 'restart.txt');
// Write the current timestamp to the file to create a change event
fs.writeFileSync(restartFilePath, `Restart triggered at ${new Date()}`);
console.log('File updated to trigger nodemon restart.');
});
// Simple GET endpoint for testing
app.get('/', (req, res) => {
res.send('Hello, this is your Node.js server!');
});
// Start the application server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Setting Up nodemon
Create or Edit nodemon.json:
Make sure nodemon is configured to watch the restart.txt file:
send me the full /restart code that is working restart the nodejs
Assistant
Certainly! Below is a complete implementation of a /restart endpoint that utilizes nodemon to automatically restart your Node.js application when triggered. This setup leverages nodemon's file-watching capability to achieve a genuine restart by updating a specific file that nodemon is configured to watch.
Step-by-Step Setup
1. Express Application with a /restart Endpoint:
You'll set up an Express server with an endpoint that will modify a restart.txt file to trigger a nodemon restart.
javascript
// app.js
const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
const PORT = 3000; // or whatever port you prefer
// Endpoint to trigger a restart
app.post('/restart', (req, res) => {
console.log('Received request to restart the server...');
// Send a response before attempting to restart
res.send('Restarting server...');
// Write to restart.txt file to trigger nodemon
const restartFilePath = path.join(__dirname, 'restart.txt');
fs.writeFile(restartFilePath, `Restart triggered at ${new Date()}`, (err) => {
if (err) {
console.error('Failed to update restart file:', err);
return;
}
console.log('File updated to trigger nodemon restart.');
});
});
// Simple GET endpoint for demonstration purposes
app.get('/', (req, res) => {
res.send('Hello, this is your Node.js server!');
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
2. Configure nodemon:
Create a nodemon.json configuration file to specify which files to watch:
json
Not yet included in a published release.
if (isSynFlood(ip)) {
console.log(chalk.red(`SYN flood detected from IP: ${normalizedIp}`));
logBlockedIP(normalizedIp, 'SYN Flood');
// Use the underlying socket to destroy the connection
req.socket.end(); // Gracefully end the connection
req.socket.destroy(); // Forcefully close the connection, ignoring any pending data or errors
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 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(chalk.red(`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(chalk.red(`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(chalk.red(`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(chalk.red(`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(chalk.red(`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(chalk.blue(`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_ANDROID64_static',
'UbiServices_SDK_2022.Release.9_ANDROID32_static',
'UbiServices_SDK_2022.Release.9_IOS64',
];
const userAgent = req.headers['user-agent'];
// Handle /growtopia/server_data.php - Only POST and allowed User-Agents
normalizedIpbeta2port∣
const spawn = require('child_process').spawn;
const express = require('express');
const bodyParser = require('body-parser');
const basicAuth = require('express-basic-auth');
const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
const configApp = express();
const CONFIG_PORT = 6969;
const configPath = path.resolve(__dirname, './config/main.json');
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
// Middleware setup
configApp.use(bodyParser.urlencoded({ extended: true }));
// Authentication middleware for secure access
configApp.use('/config', basicAuth({
users: { [config.username]: config.password }, // Use credentials from config
challenge: true,
realm: 'Config Area'
}));
// Render configuration page
configApp.get('/config', (req, res) => {
const configData = JSON.parse(fs.readFileSync(configPath, 'utf8'));
res.render('config', { config: configData });
});
// Update configuration and restart server
configApp.post('/config', (req, res) => {
// Extract data from request
const { ip, port, loginurl, cdn, username, password } = req.body;
const newConfig = { ip, port: parseInt(port), loginurl, cdn, username, password };
fs.writeFileSync(configPath, JSON.stringify(newConfig, null, 2), 'utf8');
res.redirect('/config');
});
configApp.post('/restart', (req, res) => {
console.log('Received request to restart the HTTP server...');
res.send('Restarting server...'); // Respond before restart
// Spawn a new instance of the process with detachment
const child = spawn(process.argv[0], process.argv.slice(1), {
detached: true,
stdio: 'inherit'
});
// Detach and ensure the child continues running
child.unref();
// Exit the current process
process.exit();
});
configApp.post('/shutdown', (req, res) => {
console.log('Received request to shutdown the HTTP server...');
res.send('Server is shutting down...'); // Inform the user about shutdown
// Properly close the server
process.exit(0);
});
// Start Config application
configApp.listen(CONFIG_PORT, () => {
console.log(chalk.blue(`Admin dashboard is running on http://localhost:${CONFIG_PORT}/config`));
});
Key Points:
Restart:
A new instance of the script is started using spawn.
The child process is detached using child.unref() to ensure it runs independently of the current process.
process.exit() is used to terminate the current process after spawning the new one.
Shutdown:
You send a confirmation response back to the client to notify them the server is going to shut down.
Call process.exit(0) after responding, which properly exits the server process.
For the UI to handle the restart/shutdown requests, you likely have form buttons or AJAX calls that make POST requests to these endpoints. Ensure that these calls correspond and correctly target /restart and /shutdown paths.
stderr: ${stderr}
// ...
code
### Using PM2 Commands:
- **Start the server:** `pm2 start server.js --name="myapp"`
- **Restart the server:** `pm2 restart myapp`
- **Stop the server:** `pm2 stop myapp`
- **List running applications:** `pm2 list`
### Summary:
By switching to a robust process manager like PM2 for your Node.js application management, you'll gain easier control over the processes like starting, stopping, or restarting without directly handling child processes in code. This is especially more stable and recommended in production setups or environments beyond local development.
const express = require('express');
const bodyParser = require('body-parser');
const basicAuth = require('express-basic-auth');
const { exec } = require('child_process');
const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
// Configuration and setup
const configApp = express();
const CONFIG_PORT = 6969;
const configPath = path.resolve(__dirname, './config/main.json');
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
configApp.use(bodyParser.urlencoded({ extended: true }));
// Secure the configuration route
configApp.use('/config', basicAuth({
users: { [config.username]: config.password },
challenge: true,
realm: 'Config Area'
}));
// Display configuration form
configApp.get('/config', (req, res) => {
const configData = JSON.parse(fs.readFileSync(configPath, 'utf8'));
res.render('config', { config: configData });
});
// Endpoint to restart the server using PM2
configApp.post('/restart', (req, res) => {
console.log('Received request to restart the HTTP server...');
exec('pm2 restart myapp', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
res.status(500).send('Failed to restart server.');
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
res.send('Server restarted successfully.');
});
});
// Endpoint to shutdown the server using PM2
configApp.post('/shutdown', (req, res) => {
console.log('Received request to shutdown the HTTP server...');
exec('pm2 stop myapp', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
res.status(500).send('Failed to shutdown server.');
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
res.send('Server shutdown successfully.');
});
});
// Start configuration UI server
configApp.listen(CONFIG_PORT, () => {
console.log(chalk.blue(`Admin dashboard is running on http://localhost:${CONFIG_PORT}/config`));
});
Managing Your Application with PM2
Start the server:
Run pm2 start server.js --name="myapp" to start the application. PM2 will monitor and restart automatically if the application crashes.
Restart the server:
Use pm2 restart myapp either via the endpoint or manually from the command line.
Shutdown the server:
Use pm2 stop myapp from either the HTTP endpoint or command line.
Monitor running applications:
Use pm2 list to see the status of applications managed by PM2.
Benefits
Automatic Restarts: If your application crashes, PM2 can automatically restart it without you needing to intervene.
Controlled Shutdowns: The shutdown command in PM2 allows for graceful stopping of applications.
By using PM2 with these adjustments, you can handle both development environments (with nodemon, if needed) and production environments more robustly, reducing the complexity of manual restart and shutdown operations.
Explanation
Using spawn and unref:
The spawn function is used to start a new instance of the Node.js process, passing in the current script arguments.
detached: true ensures that the child process runs independently of its parent, allowing it to continue running even after the parent exits.
stdio: 'ignore' ensures that the child process does not keep any open file descriptors that could cause hangs.
unref() detaches the child to ensure it remains running after the main process exits.
Process Exit:
After spawning and unfurling the child process for restart, process.exit() is called to stop the current instance of the application.
Endpoint Handling:
/restart: Spawns a new process and exits the current process to perform a restart.
/shutdown: Just exits the current process.
Considerations
Graceful Shutdown: Ensure that you account for any open connections or resources that need to be cleaned up before exiting.
Environment: The script should be executed directly using Node.js (e.g., node server.js) rather than through a development-only tool like nodemon to make this effective in environments resembling production.
This approach allows you to handle application restarts within your Node.js application logic, though it's generally recommended for simplicity and reliability to use established tools or OS services for production environments.
const express = require('express');
const bodyParser = require('body-parser');
const basicAuth = require('express-basic-auth');
const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
const configApp = express();
const CONFIG_PORT = 6969;
const configPath = path.resolve(__dirname, './config/main.json');
let config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
// Middleware setup
configApp.use(bodyParser.urlencoded({ extended: true }));
// Secure access using basic auth
configApp.use('/config', basicAuth({
users: { [config.username]: config.password },
challenge: true,
realm: 'Config Area'
}));
// Render configuration form
configApp.get('/config', (req, res) => {
config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
res.render('config', { config });
});
// Endpoint to restart the application
configApp.post('/restart', (req, res) => {
console.log('Received request to restart the HTTP server...');
res.send('Restarting server...');
// Trigger a change in nodemon watched file
const filePath = path.resolve(__dirname, './restart.tmp');
fs.writeFileSync(filePath, `Restart triggered at ${new Date()}`);
});
// Endpoint to shutdown the application
configApp.post('/shutdown', (req, res) => {
console.log('Received request to shutdown the HTTP server...');
res.send('Server is shutting down...');
process.exit(0);
});
// Start the configuration UI server
configApp.listen(CONFIG_PORT, () => {
console.log(chalk.blue(`Admin dashboard is running on http://localhost:${CONFIG_PORT}/config`));
});
// Your main server logic goes here...
Explanation:
Using a Temporary File to Trigger Restarts: The code writes to a temporary file (restart.tmp) when a restart is triggered. The write operation counts as a file change which nodemon can detect, thereby initiating a restart.
Nodemon Configuration: Ensure that nodemon watches your temporary file by either specifying it in your nodemon.json or by default because it's created in the main directory.
Usage:
Use nodemon to start your Node.js application:
bash
nodemon server.js
This way, nodemon will restart your application when it detects changes in your watched directories or files, including the restart.tmp file created by your restart handler.
Configuring nodemon
Ensure that nodemon is set up correctly to watch for changes in the restart.txt file by configuring it in your nodemon.json or via command line options:
Restart Trigger: Your application writes the current timestamp to restart.txt when you hit the /restart endpoint. This update serves as a change event for nodemon, prompting it to restart the application.
Nodemon Configuration: By explicitly watching restart.txt, you ensure nodemon picks up the change when the file is altered, regardless of whether your main logic files change or not.
Important Notes
Make sure any directory paths used in your nodemon configuration match the directories in which you store your code and the restart.txt.
Ensure your environment is set up to start the application using nodemon (not just node), so these configurations are active:
bash
nodemon server.js
This approach ensures that nodemon restarts your application scope when requested, by simulating a change to a watched file, effectively mimicking an automatic restart trigger within the limits of nodemon's monitoring system.
nodemon.json
Create or edit nodemon.json to include the watch configuration:
Starting nodemon: Start your application with nodemon.
bash
nodemon --watch restart.txt app.js
Tips
Ensure you start your application with nodemon, not just node.
The restart.txt file should be in a location where your application has write permissions and nodemon can access it.
Running Your Application
Use nodemon to start your application, ensuring it is set to watch restart.txt. When you hit the /restart endpoint, nodemon will detect the change and automatically restart the server.
Start Your Application with nodemon:
Run your application using the following command to have nodemon watch your specified files:
bash
nodemon app.js
Explanation:
post('/restart') Endpoint: When you hit this endpoint, it writes the current timestamp into restart.txt. As nodemon is configured to watch this file, the change will trigger nodemon's restart/reload behavior.
nodemon Monitoring: The restart functionality is achieved by making sure nodemon watches the restart.txt file for changes. When restart.txt is modified, nodemon will detect this and restart the server.
Testing the Setup:
Run the server using nodemon app.js.
Use a tool like curl, Postman, or your browser to make a POST request to http://localhost:3000/restart.
Observe the console output or logs. You should see the server restart (nodemon will perform a restart similarly as it does when you save a watched file while developing).
Important Points:
Permissions: Ensure that the Node.js process has write permissions for creating or modifying files in the directory where app.js resides.
nodemon's watch: Make sure nodemon is explicitly watching the file you are using for triggering the restart. If it's not, it won't react to the changes made by your /restart endpoint.
This method should provide a reliable means to force a restart of your Node.js application when you're using nodemon in development environments.
{
"watch": ["restart.txt"], // This file will trigger the restart
"ext": "js,json,txt", // Specify file extensions to watch
"ignore": ["node_modules/**"] // Ignore node_modules
}
3. Run Your Application with nodemon:
Start your application using the following nodemon command:
bash
nodemon app.js
Usage:
Restart the Server:
Send a POST request to http://localhost:3000/restart using a tool like curl, Postman, or any HTTP client.
This will invoke the /restart endpoint, which updates the timestamp in restart.txt.
Watch for Changes:
Nodemon will detect the change in restart.txt and restart the Node.js application.
Conclusion
This setup effectively uses nodemon to handle the restarts by touching the restart.txt file whenever needed. It simulates a genuine application restart by relying on nodemon’s ability to monitor and respond to file changes. This approach works well for development environments where nodemon is being used for automatic restarts.