-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserve.js
More file actions
51 lines (44 loc) · 1.35 KB
/
Copy pathserve.js
File metadata and controls
51 lines (44 loc) · 1.35 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
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 3000;
const BUILD_DIR = path.join(process.cwd(), 'build');
const MIME_TYPES = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'text/javascript',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.json': 'application/json',
'.ico': 'image/x-icon',
'.xml': 'application/xml',
};
const server = http.createServer((req, res) => {
let filePath = path.join(BUILD_DIR, req.url === '/' ? 'index.html' : req.url);
// Try to add .html extension if no extension exists
if (!path.extname(filePath)) {
filePath += '.html';
}
const ext = path.extname(filePath);
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
fs.readFile(filePath, (err, content) => {
if (err) {
if (err.code === 'ENOENT') {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<h1>404 Not Found</h1>');
} else {
res.writeHead(500, { 'Content-Type': 'text/html' });
res.end('<h1>500 Server Error</h1>');
}
} else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content);
}
});
});
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
console.log(`Serving files from: ${BUILD_DIR}`);
});