-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
62 lines (55 loc) · 1.83 KB
/
Copy pathserver.js
File metadata and controls
62 lines (55 loc) · 1.83 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
60
61
62
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 80;
const MIME_TYPES = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'text/javascript',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.gif': 'image/gif'
};
const server = http.createServer((req, res) => {
// Handle CORS
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range');
// Get the file path
let filePath = '.' + req.url;
if (filePath === './') {
filePath = './alrada.html';
}
// Get file extension
const extname = path.extname(filePath);
let contentType = MIME_TYPES[extname] || 'application/octet-stream';
// Read and serve the file
fs.readFile(filePath, (error, content) => {
if (error) {
if (error.code === 'ENOENT') {
res.writeHead(404);
res.end('File not found');
} else {
res.writeHead(500);
res.end('Server error: ' + error.code);
}
} else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
});
try {
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
console.log('To stop the server, press Ctrl+C');
});
} catch (error) {
if (error.code === 'EACCES') {
console.error(`Error: Port ${PORT} requires administrator privileges.`);
console.log('Try running Command Prompt as Administrator');
} else {
console.error('Error starting server:', error);
}
}