import { readdir } from "node:fs/promises";
import { join } from "node:path";
const FILES_DIR = "./files";
Bun.serve({
port: 3006,
async fetch(req) {
const url = new URL(req.url);
// Kui küsitakse juurkausta, näita failide loetelu
if (url.pathname === "/") {
try {
const files = await readdir(FILES_DIR);
let html = `
Failiserver
📁 Failid
`;
if (files.length === 0) {
html += "- Kausta ei ole ühtegi faili
";
} else {
for (const file of files) {
html += `- 📄 ${file}
`;
}
}
html += `
`;
return new Response(html, {
headers: { "Content-Type": "text/html; charset=utf-8" }
});
} catch (error) {
return new Response("Viga failide lugemisel", { status: 500 });
}
}
// Kui küsitakse faili allalaadimist
if (url.pathname.startsWith("/download/")) {
const filename = decodeURIComponent(url.pathname.slice(10));
const filepath = join(FILES_DIR, filename);
try {
const file = Bun.file(filepath);
const exists = await file.exists();
if (!exists) {
return new Response("Faili ei leitud", { status: 404 });
}
return new Response(file, {
headers: {
"Content-Disposition": `attachment; filename="${filename}"`,
}
});
} catch (error) {
return new Response("Viga faili lugemisel", { status: 500 });
}
}
return new Response("Lehte ei leitud", { status: 404 });
},
});
console.log("Failiserver töötab aadressil http://localhost:3006");