-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
executable file
·67 lines (56 loc) · 1.57 KB
/
server.js
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
66
67
#!/usr/bin/env node
require("babel-register");
require("babel-polyfill");
const http = require('http'),
fs = require('fs'),
path = require('path'),
mime = require('mime');
const chatServer = require('./server/chat_server');
let cache = {};
const send404 = response => {
response.writeHead(404, {'Content-Type': 'text/plain'});
response.write('Error 404: resource not found.');
response.end();
};
const sendFile = (response, filePath, fileContent) => {
response.writeHead(200, {
'Content-Type': mime.lookup(path.basename(filePath))
});
response.end(fileContent);
};
const serverStatic = (response, cache, absPath) => {
// check if file already in cache
if (cache[absPath]) {
// return file from cache
sendFile(response, absPath, cache[absPath]);
} else {
fs.exists(absPath, exists => {
// check if file exists
if (exists) {
// read file from disk
fs.readFile(absPath, (err, data) => {
if (err) {
send404(response);
} else {
cache[absPath] = data;
sendFile(response, absPath, data);
}
});
} else {
send404(response);
}
});
}
};
const server = http.createServer((request, response) => {
let filePath = false;
if (request.url === '/') {
filePath = 'public/index.html';
} else {
filePath = 'public' + request.url;
}
const absPath = './' + filePath;
serverStatic(response, cache, absPath);
});
server.listen(3000, () => console.log('Server listening on port 3000.'));
chatServer.listen(server);