Last active
March 28, 2025 00:46
-
-
Save saravr/4f9813c0def86867aefb15e97c099520 to your computer and use it in GitHub Desktop.
HTTP server with delay option
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const http = require('http'); | |
const fs = require('fs'); | |
const path = require('path'); | |
const url = require('url'); | |
// Parse command-line arguments | |
const args = process.argv.slice(2); | |
const baseDirectory = args[0] || '.'; // Default to current directory | |
const portArg = args.find(arg => arg.startsWith('--port=')); | |
const delayArg = args.find(arg => arg.startsWith('--delay=')); | |
// Extract port and delay values | |
const port = portArg ? parseInt(portArg.split('=')[1], 10) : 9000; | |
const delay = delayArg ? parseInt(delayArg.split('=')[1], 10) : 0; | |
// Ensure directory exists | |
if (!fs.existsSync(baseDirectory) || !fs.statSync(baseDirectory).isDirectory()) { | |
console.error(`Error: Directory "${baseDirectory}" not found.`); | |
process.exit(1); | |
} | |
// Create HTTP server | |
const server = http.createServer((req, res) => { | |
const parsedUrl = url.parse(req.url); | |
let filePath = path.join(baseDirectory, decodeURIComponent(parsedUrl.pathname)); | |
// Default to index.html if requesting root | |
if (parsedUrl.pathname === '/') { | |
filePath = path.join(baseDirectory, 'index.html'); | |
} | |
// Check if file exists | |
fs.stat(filePath, (err, stats) => { | |
if (err || !stats.isFile()) { | |
res.writeHead(404, { 'Content-Type': 'text/plain' }); | |
res.end('404 Not Found'); | |
return; | |
} | |
// Delay response if specified | |
setTimeout(() => { | |
// Determine content type | |
const ext = path.extname(filePath).toLowerCase(); | |
const contentType = { | |
'.html': 'text/html', | |
'.json': 'application/json', | |
'.js': 'application/javascript', | |
'.css': 'text/css', | |
'.png': 'image/png', | |
'.jpg': 'image/jpeg', | |
'.gif': 'image/gif', | |
'.svg': 'image/svg+xml', | |
'.txt': 'text/plain', | |
}[ext] || 'application/octet-stream'; | |
// Serve file | |
res.writeHead(200, { 'Content-Type': contentType }); | |
fs.createReadStream(filePath).pipe(res); | |
}, delay); | |
}); | |
}); | |
// Start server | |
server.listen(port, () => { | |
console.log(`Serving "${baseDirectory}" on port ${port} with ${delay}ms delay`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment