-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
50 lines (44 loc) · 1.33 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
const http = require('http');
const fs = require('fs');
const path = require('path');
const mime = require('mime-types');
const proxyMatch = /^\/proxy\/(.+)/;
if (process.env.NODE_ENV === 'development') {
require('dotenv').config({
path: path.join(__dirname, '.env.development')
});
}
const server = http.createServer((req, res) => {
if (proxyMatch.test(req.url)) {
const match = req.url.match(proxyMatch);
const url = match[1];
http.get(url, (response) => {
response.on('error', err => {
res.statusCode = 400;
res.end(err.message);
}).pipe(res);
});
} else {
// If requesting a file
if (/\.[^/]+$/.test(req.url)) {
try {
res.setHeader('Content-Type', mime.lookup(req.url));
// Try reading file
fs.createReadStream(path.join(__dirname, 'build', req.url)).on('error', err => {
res.statusCode = 404;
res.end(err.message);
}).pipe(res);
} catch (err) {
res.statusCode = 404;
res.end();
}
} else {
res.setHeader('Content-Type', 'text/html');
// Any other path, yields index.html
fs.createReadStream(path.join(__dirname, 'build/index.html')).pipe(res);
}
}
});
server.listen(process.env.PORT || 3000, () => {
console.log(`server listening on localhost:${server.address().port}`);
});