Select Git revision
dev-server.ts
-
Millicent Billette authoredMillicent Billette authored
dev-server.ts 1.17 KiB
import { serve } from 'bun';
import path from 'path';
// Try ports starting from 3000 and increment if busy
async function startServer() {
const PUBLIC_DIR = path.join(__dirname, 'public');
let port = Number(process.env.PORT || 3000);
let maxAttempts = 10;
while (maxAttempts > 0) {
try {
const server = serve({
port,
fetch(req) {
const url = new URL(req.url);
const filePath = path.join(PUBLIC_DIR, url.pathname === '/' ? 'index.html' : url.pathname);
try {
return new Response(Bun.file(filePath));
} catch {
return new Response('Not Found', { status: 404 });
}
}
});
console.log(`✅ Static server running at http://localhost:${port}`);
return;
} catch (error) {
if (String(error).includes('EADDRINUSE')) {
console.log(`Port ${port} is in use, trying ${port + 1}...`);
port++;
maxAttempts--;
} else {
console.error('Server error:', error);
process.exit(1);
}
}
}
console.error(`Could not find an available port after ${10} attempts`);
process.exit(1);
}
startServer();