serve from file instead of object
This commit is contained in:
parent
7fd4342405
commit
ea72b74447
|
|
@ -193,22 +193,50 @@ export const createServer = async () => {
|
|||
|
||||
if (core[pathname]) content = core[pathname];
|
||||
else if (site[pathname]) content = site[pathname];
|
||||
else if (pub[pathname]){
|
||||
//read content from file
|
||||
content = await Bun.file(dir(`public/${pathname}`)).text();
|
||||
//detect file type
|
||||
const fileType = await fileTypeFromBlob(Bun.file(dir(`public/${pathname}`)));
|
||||
if(fileType){
|
||||
//set content type
|
||||
opt?.headers?.set("Content-Type", fileType.mime);
|
||||
}
|
||||
else if (pub[pathname]) {
|
||||
// Serve file directly from public folder
|
||||
const filePath = dir(`public/${pathname}`);
|
||||
const file = Bun.file(filePath);
|
||||
|
||||
return new Response(content, {
|
||||
status: 200,
|
||||
headers: opt?.headers || new Headers(),
|
||||
});
|
||||
// Check if file exists
|
||||
if (!(await file.exists())) {
|
||||
return new Response("File not found", { status: 404 });
|
||||
}
|
||||
|
||||
// Detect file type
|
||||
const fileType = await fileTypeFromBlob(file);
|
||||
|
||||
// Set content type
|
||||
if (fileType) {
|
||||
opt?.headers?.set("Content-Type", fileType.mime);
|
||||
} else {
|
||||
// Fallback to extension-based MIME type detection
|
||||
const ext = pathname.split('.').pop()?.toLowerCase();
|
||||
const mimeTypes: Record<string, string> = {
|
||||
'html': 'text/html',
|
||||
'css': 'text/css',
|
||||
'js': 'application/javascript',
|
||||
'json': 'application/json',
|
||||
'png': 'image/png',
|
||||
'jpg': 'image/jpeg',
|
||||
'jpeg': 'image/jpeg',
|
||||
'gif': 'image/gif',
|
||||
'svg': 'image/svg+xml',
|
||||
'ico': 'image/x-icon',
|
||||
'txt': 'text/plain',
|
||||
};
|
||||
if (ext && mimeTypes[ext]) {
|
||||
opt?.headers?.set("Content-Type", mimeTypes[ext]);
|
||||
}
|
||||
}
|
||||
|
||||
// Return the file directly (Bun will stream it efficiently)
|
||||
return new Response(file, {
|
||||
status: 200,
|
||||
headers: opt?.headers || new Headers(),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
if (content) {
|
||||
|
|
|
|||
Loading…
Reference in New Issue