Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const http = require('http');
- const fs = require('fs').promises;
- const path = require('path');
- const url = require('url');
- const querystring = require('querystring');
- const { performance } = require('perf_hooks');
- const HOST = 'localhost';
- const PORT = 8080;
- const STATIC_DIR = path.join(__dirname, 'public');
- const MIME_TYPES = {
- '.html': 'text/html; charset=utf-8',
- '.js': 'application/javascript',
- '.css': 'text/css',
- '.json': 'application/json',
- '.png': 'image/png',
- '.jpg': 'image/jpeg',
- '.gif': 'image/gif',
- '.svg': 'image/svg+xml'
- };
- const cache = new Map();
- const requestQueue = [];
- let activeRequests = 0;
- const MAX_CONCURRENT = 100;
- const CACHE_TTL = 3600000;
- const logger = {
- log: (req, status, time) => {
- const timestamp = new Date().toISOString();
- const { method, url } = req;
- console.log(`${timestamp} ${method} ${url} ${status} ${time.toFixed(2)}ms`);
- },
- error: (err) => console.error(`[${new Date().toISOString()}] ERROR: ${err.stack}`)
- };
- const rateLimit = new Map();
- const RATE_LIMIT = 100;
- const RATE_WINDOW = 60000;
- const checkRateLimit = (ip) => {
- const now = Date.now();
- const record = rateLimit.get(ip) || { count: 0, start: now };
- if (now - record.start > RATE_WINDOW) {
- record.count = 0;
- record.start = now;
- }
- record.count++;
- rateLimit.set(ip, record);
- return record.count <= RATE_LIMIT;
- };
- const handleStaticFile = async (pathname, res) => {
- const filePath = path.join(STATIC_DIR, pathname === '/' ? 'index.html' : pathname);
- if (cache.has(filePath)) {
- const { content, mime, timestamp } = cache.get(filePath);
- if (Date.now() - timestamp < CACHE_TTL) {
- res.writeHead(200, {
- 'Content-Type': mime,
- 'Cache-Control': 'public, max-age=3600'
- });
- res.end(content);
- return true;
- }
- cache.delete(filePath);
- }
- try {
- const content = await fs.readFile(filePath);
- const ext = path.extname(filePath).toLowerCase();
- const mime = MIME_TYPES[ext] || 'application/octet-stream';
- cache.set(filePath, {
- content,
- mime,
- timestamp: Date.now()
- });
- res.writeHead(200, {
- 'Content-Type': mime,
- 'Cache-Control': 'public, max-age=3600'
- });
- res.end(content);
- return true;
- } catch (err) {
- return false;
- }
- };
- const handleApiRequest = async (req, res, pathname, query) => {
- if (pathname.startsWith('/api/')) {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({
- status: 'ok',
- path: pathname,
- query,
- timestamp: Date.now()
- }));
- return true;
- }
- return false;
- };
- const queueRequest = (req, res) => {
- return new Promise((resolve) => {
- requestQueue.push({ req, res, resolve });
- processQueue();
- });
- };
- const processQueue = () => {
- if (activeRequests >= MAX_CONCURRENT || !requestQueue.length) return;
- activeRequests++;
- const { req, res, resolve } = requestQueue.shift();
- handleRequest(req, res).finally(() => {
- activeRequests--;
- resolve();
- processQueue();
- });
- };
- const handleRequest = async (req, res) => {
- const startTime = performance.now();
- const { pathname, query } = url.parse(req.url, true);
- const ip = req.socket.remoteAddress;
- try {
- if (!checkRateLimit(ip)) {
- res.writeHead(429, { 'Content-Type': 'text/plain' });
- res.end('Rate limit exceeded');
- logger.log(req, 429, performance.now() - startTime);
- return;
- }
- res.setHeader('X-Powered-By', 'Node.js');
- res.setHeader('X-Content-Type-Options', 'nosniff');
- res.setHeader('X-Frame-Options', 'DENY');
- if (await handleApiRequest(req, res, pathname, query)) {
- logger.log(req, 200, performance.now() - startTime);
- return;
- }
- if (await handleStaticFile(pathname, res)) {
- logger.log(req, 200, performance.now() - startTime);
- return;
- }
- res.writeHead(404, { 'Content-Type': 'text/plain' });
- res.end('Not Found');
- logger.log(req, 404, performance.now() - startTime);
- } catch (err) {
- res.writeHead(500, { 'Content-Type': 'text/plain' });
- res.end('Internal Server Error');
- logger.error(err);
- logger.log(req, 500, performance.now() - startTime);
- }
- };
- const server = http.createServer((req, res) => {
- queueRequest(req, res);
- });
- server.on('error', logger.error);
- server.listen(PORT, HOST, () => {
- console.log(`Server running at http://${HOST}:${PORT}`);
- });
- process.on('SIGTERM', () => {
- server.close(() => {
- console.log('Server terminated');
- process.exit(0);
- });
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement