Skip to content

Instantly share code, notes, and snippets.

@muralikrishnat
Created December 25, 2017 10:25
Show Gist options
  • Save muralikrishnat/d1254ca35583de6e63766c2a15359d03 to your computer and use it in GitHub Desktop.
Save muralikrishnat/d1254ca35583de6e63766c2a15359d03 to your computer and use it in GitHub Desktop.
Node JS script as static server and proxy server
var static = require('node-static');
var rootRequest = require('request');
var fs = require('fs');
var path = require('path');
var buildInProgress = false;
module.exports = function(options) {
console.log('options', options);
var baseUrl = 'https://dev.azurewebsites.net';
let origin = 'http://localhost:4200';
if (options.endpoint && options.endpoint.toLowerCase() === 'uat'.toLowerCase()) {
baseUrl = 'http://uat.azurewebsites.net';
origin = 'https://uat.azurewebsites.net';
}
var requestOptions = {
url: '',
headers: {
'Content-Type': 'application/json',
'Origin': origin
},
method: 'POST',
json: true,
body: {}
};
fePort = options.fePort;
folder = options.folder || 'master';
var server = require('http').createServer((request, response) => {
var body = [];
if (request.url.indexOf('api') >= 0) {
request.on('data', function(chunk) {
body.push(chunk);
});
}
request.addListener('end', function() {
if (request.method === 'OPTIONS') {
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Allow-Headers', 'Content-Type, x-api-key');
response.writeHead(200, {
'Content-Type': 'application/json'
});
response.end();
} else if (request.url.indexOf('api') >= 0) {
body = Buffer.concat(body).toString();
try {
body = JSON.parse(body);
} catch (e) {}
requestOptions.url = baseUrl + request.url;
requestOptions.body = body;
requestOptions.method = request.method;
if (request.headers['authorization']) {
requestOptions.headers['authorization'] = request.headers['authorization'];
}
if (request.headers['Authorization']) {
requestOptions.headers['Authorization'] = request.headers['Authorization'];
}
if (request.headers['X-API-Key']) {
requestOptions.headers['X-API-Key'] = request.headers['X-API-Key'];
}
if (request.headers['X-API-Key'.toLowerCase()]) {
requestOptions.headers['X-API-Key'] = request.headers['X-API-Key'.toLowerCase()];
}
console.log(`[LOG ${requestOptions.method} ] : ${requestOptions.url}`);
console.log(`[Request Details] : ` + JSON.stringify(requestOptions.headers));
rootRequest(requestOptions, (err, resp, rootBody) => {
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Expose-Headers', 'Authorization, Location, authorization');
if (resp.headers['authorization']) {
response.setHeader('authorization', resp.headers['authorization']);
}
if (resp.headers['Authorization']) {
response.setHeader('Authorization', resp.headers['Authorization']);
}
response.writeHead(resp.statusCode, {
'Content-Type': 'application/json'
});
if (rootBody) {
response.write(JSON.stringify(rootBody))
}
response.end();
});
} else {
var file = new static.Server('./' + folder, { headers: { gzip: true } });
if (request.url.indexOf('.gz') >= 0) {
console.log('serving from gzip', request.url);
var headers = { 'Content-Encoding': 'gzip' };
if (request.url.indexOf('.css') >= 0) {
headers['Content-Type'] = 'text/css';
}
file.serveFile('/' + request.url, 200, headers, request, response);
} else {
file.serve(request, response, function(err, res) {
if (err && (err.status === 404) && request.url.indexOf('.html') < 0) {
fs.exists(path.join(__dirname, folder, 'index.html'), (exists) => {
if (exists) {
file.serveFile('/index.html', 200, {}, request, response);
} else {
response.writeHead(200, { 'content-type': 'text/html' });
response.end('Build in progress.......');
}
});
} else {
response.writeHead(200, { 'content-type': 'text/html' });
response.end('Resource Not Found');
}
});
}
}
}).resume();
}).listen(fePort, () => {
console.log('Server Listining on ' + fePort);
})
};
let port = 80,
folder = 'dist',
endpoint = "dev";
if (process.argv) {
process.argv.forEach((p) => {
if (p.indexOf('--port=') >= 0) {
port = parseInt(p.split('=')[1]);
}
});
process.argv.forEach((p) => {
if (p.indexOf('--folder=') >= 0) {
folder = p.split('=')[1];
}
});
process.argv.forEach((p) => {
if (p.indexOf('--endpoint=') >= 0) {
endpoint = p.split('=')[1];
}
});
}
require('./fe-server')({ fePort: port, folder, endpoint: endpoint });
// Run below command in terminal
// node index.js --port=4200 --endpoint=dev
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment