-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
60 lines (48 loc) · 1.79 KB
/
server.ts
File metadata and controls
60 lines (48 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { serve, RequestHandler } from 'bun';
import { join, resolve } from 'path';
import { readFileSync, existsSync } from 'fs';
import { config } from 'dotenv';
import mime from 'mime';
// Load environment variables from .env file
config();
// Get the DOCS directory from environment variables
const { DOCS } = process.env as { DOCS: string };
// Define the directory to serve
const docsDir = resolve(DOCS);
const handler: RequestHandler = (request) => {
const url = new URL(request.url);
let filePath = resolve(join(docsDir, url.pathname));
console.log(`Request URL: ${url.pathname}`);
console.log(`File Path: ${filePath}`);
// Default to serving index.html for root and directories
if (url.pathname === '/' || url.pathname.endsWith('/')) {
filePath = join(filePath, 'index.html');
}
console.log(`Final File Path: ${filePath}`);
// Check if the file exists
if (existsSync(filePath)) {
// Try to read and return the file content
try {
// Determine the content type based on file extension
const contentType = mime.getType(filePath) || 'text/plain';
// Read file contents as a buffer
const content = readFileSync(filePath);
return new Response(content, {
headers: { 'Content-Type': contentType },
});
} catch (err) {
console.error(`Error reading file: ${err}`);
// If there's an error reading the file, return a 500 response
return new Response('Internal Server Error', { status: 500 });
}
} else {
console.error('File not found');
// If the file does not exist, return a 404 response
return new Response('File not found', { status: 404 });
}
};
serve({
fetch: handler,
port: 8000, // You can change the port if needed
});
console.log(`Serving files from ${docsDir} on http://localhost:8000`);