-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathserver.js
More file actions
42 lines (38 loc) · 1.27 KB
/
server.js
File metadata and controls
42 lines (38 loc) · 1.27 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
const http = require('http');
const fs = require('fs');
const path = require('path');
const mime = require('mime-types');
const PORT = process.env.PORT || 5000;
const HOST = '127.0.0.1'; // Listen on localhost
const publicDir = path.join(__dirname);
const server = http.createServer((req, res) => {
const urlPath = req.url.split('?')[0];
const url = (urlPath === '/') ? '/index.html' : urlPath;
const filePath = path.join(publicDir, url);
const contentType = mime.lookup(filePath) || 'application/octet-stream';
fs.readFile(filePath, (err, content) => {
if (err) {
if (err.code === 'ENOENT') {
// File not found
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
} else {
// Server error
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end(`500 Internal Server Error: ${err.code}`);
}
} else {
// Success
res.writeHead(200, {
'Content-Type': contentType,
'Content-Length': content.length,
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp'
});
res.end(content);
}
});
});
server.listen(PORT, HOST, () => {
console.log(`Server is running on http://${HOST}:${PORT}`);
});