-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathserver.js
More file actions
41 lines (35 loc) · 1.03 KB
/
server.js
File metadata and controls
41 lines (35 loc) · 1.03 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
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = process.env.PORT || 3000;
const server = http.createServer((req, res) => {
const filePath = path.join(__dirname, req.url === '/' ? 'index.html' : req.url);
const extname = path.extname(filePath);
const contentTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.gif': 'image/gif'
};
const contentType = contentTypes[extname] || 'text/plain';
fs.readFile(filePath, (err, content) => {
if (err) {
if (err.code === 'ENOENT') {
res.writeHead(404);
res.end(`File not found: ${filePath}`);
} else {
res.writeHead(500);
res.end(`Server error: ${err.code}`);
}
} else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
});
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});