Skip to content

Instantly share code, notes, and snippets.

@pedro
Created May 20, 2010 23:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pedro/408254 to your computer and use it in GitHub Desktop.
Save pedro/408254 to your computer and use it in GitHub Desktop.
var sys = require('sys'),
http = require('http'),
spawn = require('child_process').spawn
// this is a simple proxy
http.createServer(function(req, res) {
// and here is the problem: if I try to do any IO before
// proxying (like making another request or spawning) it
// freezes the whole thing.
doRequest(function() { // change to doRequest or doSpawn and watch it happen
sys.puts('proxying google.com')
var google = http.createClient(80, 'google.com');
var googleReq = google.request('GET', '/', { 'host': 'google.com' });
googleReq.addListener('response', function (googleRes) {
res.writeHead(googleRes.statusCode, googleRes.headers)
googleRes.addListener('data', function(chunk) {
sys.puts('\trecv ' + chunk.length)
res.write(chunk, 'binary')
})
googleRes.addListener('end', function() {
res.end()
})
})
req.addListener('data', function(chunk) {
sys.puts('\tsend ' + chunk.length)
googleReq.write(chunk, 'binary')
})
req.addListener('end', function() {
googleReq.end()
})
})
}).listen(8000)
function doNothing(callback) {
callback()
}
function doRequest(callback) {
var node = http.createClient(80, 'nodejs.org');
var nodeReq = node.request('GET', '/', { 'host': 'nodejs.org' });
nodeReq.addListener('response', function (site1Res) {
sys.puts('got a response from nodejs.org')
callback()
})
nodeReq.end()
}
function doSpawn(callback) {
var ls = spawn('ls')
ls.addListener('exit', function(code) {
sys.puts('ls exited with ' + code)
callback()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment