哪个node.js HTTP代理实现更高效?

时间:2011-10-29 01:49:06

标签: http node.js proxy stream benchmarking

以下哪个node.js HTTP代理实现更具性能?

第一个实现是:

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);

第二个使用stream.pipe(),它就像:

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);

1 个答案:

答案 0 :(得分:5)

如果文件很大且客户端连接速度很慢或者上传的文件太大而服务器上传带宽很小,则第一个可能会破坏您的进程。使用pipe,它专为此类内容而设计。

另外,使用npm中的现有模块: