-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
83 lines (76 loc) · 2.19 KB
/
server.js
File metadata and controls
83 lines (76 loc) · 2.19 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/* eslint arrow-parens: ["error", "as-needed"]*/
const http = require('http'); // built in http module
const fs = require('fs');
// built in path module for filesystem and path related functionalities
const path = require('path');
// Add-on mime module to derive mime based extensions
const mime = require('mime');
// Object to store cached files
const cache = {};
const chatServer = require('./lib/chat_server');
/**
* Helper function for handling 404 errors when a file is
* requested that doesn't exist
*/
const send404 = response => {
response.writeHead(404, { 'Content-Type': 'text/plain' });
response.write('Error 404 : resource not found.');
response.end();
};
/**
* Helper function to serve file data.
* Function writes the appropriate HTTP headers and then
* sends the contents of the file
*/
const sendFile = (response, filePath, fileContents) => {
response.writeHead(200, {
'Content-Type': mime.lookup(path.basename(filePath)),
});
response.end(fileContents);
};
/**
* a helper function for providing data either from cache if available
* else from disk and also caching in the process
*/
const serverStatic = (response, absPath) => {
// Check if file exists in cache memory
if (cache[absPath]) {
// Serve file from cache memorys
sendFile(response, absPath, cache[absPath]);
} else {
// check if file exists
fs.exists(absPath, exists => {
if (exists) {
fs.readFile(absPath, (err, data) => {
if (err) {
send404(response);
} else {
cache[absPath] = data;
sendFile(response, absPath, data);
}
});
} else {
send404(response);
}
});
}
};
/**
* Server Object which listens for request and provides appropriate
* response using helper functions
*/
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, absPath);
});
server.listen(3000, () => {
console.log('server just started on port 3000');
});
// listening for chat actions
chatServer.listen(server);