Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
80 lines (63 loc) · 1.88 KB
/
Copy pathapp.js
File metadata and controls
80 lines (63 loc) · 1.88 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
const OSC = require('osc-js')
const config = { udpClient: { port: 9129 } }
const osc = new OSC({ plugin: new OSC.BridgePlugin(config) })
osc.open() // start a WebSocket server on port 8080
const fs = require('fs');
const http = require('http');
const path = require('path');
const port = 8000;
const directoryName = './';
const types = {
html: 'text/html',
css: 'text/css',
js: 'application/javascript',
png: 'image/png',
jpg: 'image/jpeg',
jpeg: 'image/jpeg',
gif: 'image/gif',
json: 'application/json',
xml: 'application/xml',
};
const root = path.normalize(path.resolve(directoryName));
const server = http.createServer((req, res) => {
console.log(`${req.method} ${req.url}`);
const extension = path.extname(req.url).slice(1);
const type = extension ? types[extension] : types.html;
const supportedExtension = Boolean(type);
if (!supportedExtension) {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('404: File not found');
return;
}
let fileName = req.url;
if (req.url === '/') fileName = 'index.html';
else if (!extension) {
try {
fs.accessSync(path.join(root, req.url + '.html'), fs.constants.F_OK);
fileName = req.url + '.html';
} catch (e) {
fileName = path.join(req.url, 'index.html');
}
}
const filePath = path.join(root, fileName);
const isPathUnderRoot = path
.normalize(path.resolve(filePath))
.startsWith(root);
if (!isPathUnderRoot) {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('404: File not found');
return;
}
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('404: File not found');
} else {
res.writeHead(200, { 'Content-Type': type });
res.end(data);
}
});
});
server.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});