Last active
August 24, 2020 20:31
Reverse proxy server for serving bundled assets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var httpProxy = require('http-proxy'), | |
fs = require('fs'), | |
http = require('http'), | |
url = require('url'), | |
path = require('path'), | |
iconv = require('iconv-lite'); | |
var proxy = httpProxy.createProxyServer({}); | |
proxy.on('error', function(e) { | |
console.log(e); | |
}); | |
var mime = { | |
html: 'text/html', | |
txt: 'text/plain', | |
css: 'text/css', | |
gif: 'image/gif', | |
jpg: 'image/jpeg', | |
png: 'image/png', | |
svg: 'image/svg+xml', | |
js: 'application/javascript', | |
// ttf: 'font/ttf', | |
ttf: 'application/octet-stream', | |
woff: 'application/font-woff', | |
woff2: 'application/font-woff2' | |
}; | |
http.createServer(function (req, res) { | |
if (/\/api\/|\/app\/auth\//.exec(req.url)) { | |
console.log(`proxying request ${req.url}`) | |
proxy.web(req, res, { target: 'http://benchprep.localhost' }); | |
} | |
else { | |
let file; | |
if (/\/app\//.exec(req.url)) { | |
console.log(`requesting local file ${req.url}`) | |
file = url.parse(req.url).pathname; | |
} else { | |
console.log(`requesting index ${req.url}`) | |
file = '/index.html' | |
} | |
var type = mime[path.extname(file).slice(1)] || 'text/plain'; | |
console.log(`reading path ${__dirname + file} of mime type ${type}`); | |
var s = fs.createReadStream(__dirname + file); | |
s.on('open', function () { | |
var stats = fs.statSync(__dirname + file) | |
var fileSizeInBytes = stats["size"] | |
res.setHeader('Content-Type', type); | |
res.setHeader('Vary', 'Accept-Encoding'); | |
if (/\/app\/assets\/benchprep-assets\/fonts\//.exec(req.url)) { | |
s | |
.pipe(iconv.decodeStream('utf-8')) | |
.pipe(iconv.encodeStream('utf-16')) | |
.pipe(res); | |
} | |
else { | |
s.pipe(res); | |
} | |
}); | |
s.on('error', function () { | |
res.setHeader('Content-Type', 'text/plain'); | |
res.statusCode = 404; | |
res.end('Not found'); | |
}); | |
} | |
}).listen(8080); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment