Created
December 13, 2014 01:40
-
-
Save FesterCluck/022a229615a4a348c361 to your computer and use it in GitHub Desktop.
Local Web Server + Proxy Relay
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 sys = require("sys"), | |
http = require('http'), | |
path = require("path"), | |
url = require("url"), | |
filesys = require("fs"); | |
http.createServer(function(request, response) { | |
var my_path = url.parse(request.url).pathname; | |
var full_path = path.join(process.cwd(),my_path); | |
path.exists(full_path,function(exists){ | |
if(!exists){ | |
var proxy_request = http.request({ | |
host: "en.wikipedia.org", | |
port: 80, | |
path: my_path, | |
method: request.method | |
}, function(proxy_response) { | |
proxy_response.addListener('data', function(chunk) { | |
response.write(chunk, 'binary'); | |
}); | |
proxy_response.addListener('end', function() { | |
response.end(); | |
}); | |
response.writeHead(proxy_response.statusCode, proxy_response.headers); | |
}); | |
request.addListener('data', function(chunk) { | |
proxy_request.write(chunk, 'binary'); | |
}); | |
request.addListener('end', function() { | |
proxy_request.end(); | |
}); | |
} | |
else{ | |
filesys.readFile(full_path, "binary", function(err, file) { | |
if(err) { | |
response.writeHeader(500, {"Content-Type": "text/plain"}); | |
response.write(err + "\n"); | |
response.end(); | |
} | |
else{ | |
response.writeHeader(200); | |
response.write(file, "binary"); | |
response.end(); | |
} | |
}); | |
} | |
}); | |
}).listen(8080); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment