Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which node.js HTTP proxy implementation is more performant?

Which one of the following node.js HTTP proxy implementations is more performant?

The first implementation is:

var http = require('http');

http.createServer(function(request, response) {
  var proxy = http.createClient(80, "google.com")
  var proxy_request = proxy.request(request.method, request.url, request.headers);
  proxy_request.addListener('response', 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();
  });
}).listen(8080);

The second one uses stream.pipe() and it's like:

var http = require('http');

http.createServer(function(request, response) {
  var proxy = http.createClient(80, "google.com");
  var proxy_request = proxy.request(request.method, request.url, request.headers);
  proxy_request.on('response', function (proxy_response) {
        proxy_response.pipe(response);
        response.writeHead(proxy_response.statusCode, proxy_response.headers);
  });

  request.pipe(proxy_request);
}).listen(8080);
like image 655
Mark Avatar asked Mar 21 '26 14:03

Mark


1 Answers

The first one might blow up your process if the file is big and the clients connection is slow or if an uploaded file is big and the servers upload bandwidth is small. Use pipe, it's designed for this kind of stuff.

Also, use an existing module from npm for this:

  • many features and used in production at nodejitsu: http-proxy
  • fast: bouncy
like image 139
thejh Avatar answered Mar 24 '26 05:03

thejh