Created
December 24, 2013 18:10
-
-
Save kurtroberts/8116407 to your computer and use it in GitHub Desktop.
For the first useful thing I ever built in node, I hacked together this reverse proxy script so that I could fiddle with front-end code on a remote website more easily. It sits between your computer and the remote site, checking first for files in a folder you specify, then trying a GET request against the site.
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 http = require('http'), | |
path = require('path'), | |
fs = require('fs'), | |
localPath = "/PATH/TO/LOCAL/FOLDER/", | |
remoteServer = { host: 'www.example.com', | |
port: 80 | |
}, | |
mimeTypes = { 'js' : 'text/javascript', | |
'css' : 'text/css', | |
'html' : 'text/html', | |
'png': 'image/png' }, | |
queryStringRE = /\?.*$/; | |
http.createServer(function (req, res) { | |
var localfile = path.normalize(localPath + req.url.replace(queryStringRE, '')); | |
path.exists(localfile, function (exists) { | |
if (exists && localfile != localPath) { | |
console.log('Serving local file: ' + localfile); | |
fs.readFile(localfile, function (err, data) { | |
res.writeHead("200", {'Content-Type': mimeTypes[path.extname(req.url)]}); | |
res.write(data); | |
res.end(); | |
}); | |
} else { | |
console.log('No local file: ' + path.normalize(localPath + req.url) + ', serving remote.'); | |
remoteServer.path = req.url; | |
remoteServer.method = req.method; | |
http.request(remoteServer, function(remoteRes) { | |
res.writeHead(remoteRes.statusCode, remoteRes.headers); | |
remoteRes.on("data", function (chunk) { | |
res.write(chunk); | |
}).on("end", function () { | |
res.end(); | |
}); | |
}).on('error', function(e) { | |
console.log("Got error: " + e.message); | |
}).end(); | |
} | |
}); | |
}).listen(8080, '127.0.0.1'); | |
console.log('Server running at http://127.0.0.1:8080/'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment