-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
58 lines (49 loc) · 1.67 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
/* global EventSource */
var fs = require('fs')
var http = require('http')
var https = require('https')
var inject = require('script-injector')
var mime = require('mime')
var proxy = require('http-proxy').createProxyServer()
var url = require('url')
function reload () {
(new EventSource('/_reload')).onmessage = function (e) {
window.location.reload(true)
}
}
var apiurl = url.parse(process.env.APIURL || 'https://wavefarm.org/api/')
var agent = (apiurl.protocol === 'http:' ? http.globalAgent : https.globalAgent)
proxy.on('error', function (err, req, res) {
console.error('API', err.message)
res.statusCode = 502
res.end('{"message": "Bad Gateway"}')
})
http.createServer(function (req, res) {
console.log(req.method, req.url)
var path = url.parse(req.url).pathname
if (path.indexOf('/api/') === 0) {
req.url = req.url.replace('/api', '')
return proxy.web(req, res, {
target: apiurl,
agent: agent,
headers: {host: apiurl.hostname}
})
}
// Serve everything else from /admin/
if (path.indexOf('/admin/') !== 0) {
console.warn(404)
res.statusCode = 404
return res.end('Not Found')
}
path = path.replace('/admin', '')
res.setHeader('Content-Type', mime.lookup(path) + '; charset=utf-8')
var fileStream = fs.createReadStream('static' + path)
fileStream.pipe(res)
// If we can't create a stream (because file doesn't exist) send the index
fileStream.on('error', function () {
res.setHeader('Content-Type', 'text/html; charset=utf-8')
return fs.createReadStream('static/index.html').pipe(inject(reload)).pipe(res)
})
}).listen(process.env.PORT || 1040, function () {
if (process.send) process.send('online')
})