Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing net/http to use c-ares instead of getaddrinfo()

Tags:

http

node.js

dns

As the doc says:

All methods in the dns module use C-Ares except for dns.lookup which uses getaddrinfo(3) in a thread pool.

However, the net and http modules always use dns.lookup. Is there a way to change this ? getaddrinfo is synchronous and the pool will only allow 4 concurrent requests.

like image 775
Laurent Perrin Avatar asked Oct 04 '13 15:10

Laurent Perrin


1 Answers

After looking into this, it seems the only way is to do the DNS request manually. I use something like this:

var dns = require('dns'),
    http = require('http');

function httpRequest(options, body, done) {
  var hostname = options.hostname || options.host;

  if (typeof(body) === 'function') {
    done = body;
    body = null;
  }

  // async resolve with C-ares
  dns.resolve(hostname, function (err, addresses) {
    if (err)
      return done(err);

    // Pass the host in the headers so the remote webserver
    // can use the correct vhost.
    var headers = options.headers || {};
    headers.host = hostname;
    options.headers = headers;

    // pass the resolved address so http doesn't feel the need to
    // call dns.lookup in a thread pool
    options.hostname = addresses[0];
    options.host = undefined;

    var req = http.request(options, done);

    req.on('error', done);

    if (body)
      req.write(body);

    req.end();
  });
}
like image 81
Laurent Perrin Avatar answered Oct 25 '22 16:10

Laurent Perrin