Guest User

Untitled

a guest
May 26th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. var sys = require('sys'),
  2. http = require('http'),
  3. spawn = require('child_process').spawn
  4.  
  5. // this is a simple proxy
  6. http.createServer(function(req, res) {
  7.  
  8. // and here is the problem: if I try to do any IO before
  9. // proxying (like making another request or spawning) it
  10. // freezes the whole thing.
  11. doRequest(function() { // change to doRequest or doSpawn and watch it happen
  12. sys.puts('proxying google.com')
  13. var google = http.createClient(80, 'google.com');
  14. var googleReq = google.request('GET', '/', { 'host': 'google.com' });
  15.  
  16. googleReq.addListener('response', function (googleRes) {
  17. res.writeHead(googleRes.statusCode, googleRes.headers)
  18. googleRes.addListener('data', function(chunk) {
  19. sys.puts('\trecv ' + chunk.length)
  20. res.write(chunk, 'binary')
  21. })
  22. googleRes.addListener('end', function() {
  23. res.end()
  24. })
  25. })
  26.  
  27. req.addListener('data', function(chunk) {
  28. sys.puts('\tsend ' + chunk.length)
  29. googleReq.write(chunk, 'binary')
  30. })
  31. req.addListener('end', function() {
  32. googleReq.end()
  33. })
  34. })
  35. }).listen(8000)
  36.  
  37. function doNothing(callback) {
  38. callback()
  39. }
  40.  
  41. function doRequest(callback) {
  42. var node = http.createClient(80, 'nodejs.org');
  43. var nodeReq = node.request('GET', '/', { 'host': 'nodejs.org' });
  44.  
  45. nodeReq.addListener('response', function (site1Res) {
  46. sys.puts('got a response from nodejs.org')
  47. callback()
  48. })
  49. nodeReq.end()
  50. }
  51.  
  52. function doSpawn(callback) {
  53. var ls = spawn('ls')
  54. ls.addListener('exit', function(code) {
  55. sys.puts('ls exited with ' + code)
  56. callback()
  57. })
  58. }
Add Comment
Please, Sign In to add comment