-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
65 lines (51 loc) · 1.46 KB
/
server.js
File metadata and controls
65 lines (51 loc) · 1.46 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
63
64
65
const http = require('http'),
fs = require('fs'),
path = require('path'),
mime = require('mime-types');
const cache = {};
function send404(res) {
res.writeHead(404, {
'Content-type': 'text/html; charset=utf-8'
});
res.write('Błąd 404');
res.end();
}
function sendFile(res, filePath, fileContents) {
res.writeHead(200, {
'Content-type': mime.lookup(path.basename(filePath))
});
res.end(fileContents);
}
function serveStatic(res, cache, absPath) {
if (cache[absPath]) {
sendFile(res, absPath, cache[absPath]);
} else {
fs.exists(absPath, (exists) => {
if (exists) {
fs.readFile(absPath, (err, data) => {
if (err) {
send404(res);
} else {
cache[absPath] = data;
sendFile(res, absPath, cache[absPath]);
}
});
} else {
send404(res);
}
});
}
}
const server = http.createServer((req, res) => {
let filePath = false;
if (req.url === '/') {
filePath = 'public/index.html';
} else {
filePath = `public${ req.url }`;
}
const absPath = `./${ filePath }`;
serveStatic(res, cache, absPath);
});
server.listen(3000, () => console.log('Server running at port 3000'));
const chatServer = require('./lib/chat_server');
chatServer.listen(server);