-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebServer.js
72 lines (61 loc) · 1.59 KB
/
WebServer.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
68
69
70
71
72
const http = require('http');
const fs = require('fs');
class WebServer {
constructor() {
this.pages = new Array();
}
start(port) {
http.createServer((req, res) => {
this.serveFile(req.url, (data, err) => {
if (err) {
res.end(err.message);
return;
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
res.end();
});
}).listen(port, () => {
console.log(`Webserver started at http://localhost:${port}`);
});
}
addPath(path, file) {
this.pages.push(
{
'path': path,
'associated_file': file
}
);
}
serveFile(url, callback) {
let index = 0;
let data, err;
let found = false;
for (index = 0; index < this.pages.length; index++) {
const page = this.pages[index];
// Check for the page exist
if (page.path == url) {
try {
data = fs.readFileSync(`public/${page.associated_file}`, 'utf8');
} catch (error) {
// The path exist but the file doesn't exist
err = new Error(error.message);
}
// Whatever the values
// We send the callback
return callback(data, err);
}
}
// Looking for static files
try {
const realPath = url.substring(1);
data = fs.readFileSync(realPath, 'utf8');
return callback(data, null);
} catch (error) {
// The path and static file don't exist at all
err = new Error(`The path: ${url} doesn't exist!`);
}
return callback('null', err);
}
}
module.exports = WebServer;