Files

20 lines
1.3 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
PORT="${1:-3000}"
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$ROOT_DIR"
if command -v python3 >/dev/null 2>&1; then
exec python3 -m http.server "$PORT" --directory "$ROOT_DIR"
elif command -v python >/dev/null 2>&1; then
exec python -m SimpleHTTPServer "$PORT"
elif command -v node >/dev/null 2>&1; then
exec node -e "const http=require('http'); const fs=require('fs'); const path=require('path'); const root=process.argv[1]; const port=Number(process.argv[2]); const mime={'.html':'text/html','.js':'text/javascript','.css':'text/css','.json':'application/json','.png':'image/png','.jpg':'image/jpeg','.jpeg':'image/jpeg','.svg':'image/svg+xml','.ico':'image/x-icon'}; http.createServer((req,res)=>{let url=decodeURIComponent(req.url.split('?')[0]); if(url==='/' ) url='/'; let filePath=path.join(root,url); fs.stat(filePath,(err,stat)=>{if(!err&&stat.isDirectory()) filePath=path.join(filePath,'index.html'); fs.readFile(filePath,(err,data)=>{if(err){res.statusCode=404; return res.end('Not Found');} res.setHeader('Content-Type', mime[path.extname(filePath)]||'application/octet-stream'); res.end(data);});});}).listen(port,()=>console.log('Serving '+root+' on http://localhost:'+port));" "$ROOT_DIR" "$PORT"
else
echo "Error: python3, python, or node is required to serve the project root." >&2
exit 1
fi