-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
69 lines (59 loc) · 1.54 KB
/
app.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
'use strict';
const http = require('http');
const path = require('path');
const fs = require('fs');
const hostname = '127.0.0.1';
const port = 3000;
const fileType = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'text/javascript',
'.json': 'application/json',
'.ico': 'image/x-icon',
'.png': 'image/png'
};
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.statusCode = 302; //redirect
res.setHeader('Location', '/matrices');
res.end();
return;
}
let page = req.url;
let pathname;
let ext = path.extname(req.url);
if (req.url === '/matrices') {
page = '/matrix.html';
ext = '.html';
}
if (req.url === '/graphs') {
page = '/graph.html';
ext = '.html';
}
if (fileType[ext] === 'text/html') {
pathname = path.join(__dirname, 'public', 'pages', page);
} else if (fileType[ext] === 'text/css') {
pathname = path.join(__dirname, 'public', page);
} else if (fileType[ext] === 'text/javascript') {
pathname = path.join(__dirname, 'public', page);
}
fs.exists(pathname, exist => {
if (!exist) {
res.statusCode = 404;
res.end(`File ${pathname} not found!`);
} else {
fs.readFile(pathname, (err, data) => {
if (err) {
res.statusCode = 500;
res.end(`Error getting the file: ${err}.`);
} else {
res.setHeader('Content-type', fileType[ext]);
res.end(data);
}
});
}
});
});
server.listen(port, hostname, () => {
console.log(`Starting on ${hostname}:${port}`);
});