-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathserver.js
43 lines (36 loc) · 1.16 KB
/
server.js
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
import http from 'http';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
// Get the directory name from import.meta.url
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const PORT = process.env.PORT || 3000;
const mimeTypes = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'application/javascript',
'.ico': 'image/x-icon',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.svg': 'image/svg+xml',
};
const server = http.createServer((req, res) => {
let filePath = '.' + req.url;
if (filePath == './') filePath = './public/index.html'; // Default to index.html
const extname = String(path.extname(filePath)).toLowerCase();
const contentType = mimeTypes[extname] || 'application/octet-stream';
fs.readFile(path.join(__dirname, filePath), (err, content) => {
if (err) {
res.writeHead(404);
res.end('Sorry, we couldn\'t find that!');
} else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content);
}
});
});
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});