Skip to content

Instantly share code, notes, and snippets.

@starstuck
Created November 1, 2013 15:05
Show Gist options
  • Save starstuck/7266806 to your computer and use it in GitHub Desktop.
Save starstuck/7266806 to your computer and use it in GitHub Desktop.
Simple forward proxy in node.js, which intercept calls and let you add custom scripts to live sites/web apps. In this example it is adding skewer script, so you can mess around with live pages from emacs.
/**
* To run it you will need to install
*
* $ npm install http-proxy
*/
var http = require('http'),
httpProxy = require('http-proxy'),
port = 3001,
proxiedHost = 'localhost',
proxiedPort = 3000,
server;
function filterResponseBody(res, filter) {
var forward = res.write.bind(res);
res.write = function(chunk) {
forward(filter(chunk));
};
}
server = httpProxy.createServer(function(req, res, proxy) {
proxy.proxyRequest(req, res, {
host: proxiedHost,
port: proxiedPort
});
});
server.proxy.on('start', function(req, res, response) {
console.log(req.headers.host, req.method, req.url);
if (req.url.match(/^\/(htmlcharts|htmlchartsviewer-weblib)\/(\?|$)/)) {
filterResponseBody(res, function(chunk) {
return String.prototype.replace.call(chunk, '<head>', '<head>\n <script src="localhost:8080/skewer"></script>');
});
}
});
server.listen(port);
console.log("Started forward proxy. Go to http://localhost:" + port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment