-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
67 lines (53 loc) · 1.56 KB
/
server.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
var http = require('http');
var fs = require('fs');
var url = require('url');
var path = require('path');
var ROOT = __dirname + '/build/';
http.createServer(function(req, res) {
sendFileSafe(url.parse(req.url).pathname, res);
}).listen(8080);
function sendFileSafe(filePath, res) {
try {
filePath = decodeURIComponent(filePath);
} catch (e) {
res.statusCode = 400;
res.end("Bad Request");
return;
}
if (~filePath.indexOf('\0')) {
res.statusCode = 400;
res.end("Bad Request");
return;
}
if (filePath.indexOf('.') < 0) {
filePath = '/index.html';
}
if (filePath.indexOf('/tpm') === 0 || filePath.indexOf('/ap') === 0) {
filePath = filePath.slice(4);
}
filePath = path.normalize(path.join(ROOT, filePath));
fs.stat(filePath, function(err, stats) {
if (err || !stats.isFile()) {
res.statusCode = 404;
fs.readFile(path.normalize(path.join(ROOT, '/error-404.html')), function(err, content) {
res.end(content)
});
return;
}
sendFile(filePath, res);
});
}
function sendFile(filePath, res) {
var file = new fs.ReadStream(filePath);
var mime = require('mime').lookup(filePath);
res.setHeader('Content-Type', mime + "; charset=utf-8");
file.pipe(res);
file.on('error', function(err) {
res.end('Server Error');
console.error(err);
});
res.on('close', function() {
file.destroy();
});
}
console.log("Server is listening!");