-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
59 lines (45 loc) · 1.14 KB
/
server.js
File metadata and controls
59 lines (45 loc) · 1.14 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
'use strict';
const PORT_NUM = 8080;
const HTTP = require('http');
const URL = require('url');
const FS = require('fs');
HTTP.createServer((req, res) => {
// Decode the url:
const url = URL.parse(req.url, true)
let path = url.pathname.slice(1);
if (path.length == 0) { path = 'index.html'; }
FS.access(path, (err) => {
if (err || path.includes('..')) {
path = 'index.html';
}
});
const ctype = contentTypes[path.split('.').pop().toLowerCase()];
const query = url.query;
console.log(url, path, ctype);
// Respond to a request:
if (req.method == 'GET') {
// Clean the path argument:
FS.readFile(path, (err, data) => {
if (err) {
console.error(err);
res.statusCode = 400;
} else {
res.writeHead(200, {'Content-Type': ctype});
res.write(data);
}
res.end();
});
} else {
res.statusCode = 404;
res.end();
}
}).listen(PORT_NUM);
const contentTypes = {
'html': 'text/html',
'js': 'text/javascript',
'css': 'text/css',
'png': 'image/png',
'ico': 'image/png',
'wav': 'audio/wav',
'mp3': 'audio/mpeg',
}