首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >迫使net/http使用c-ares而不是getaddrinfo()

问迫使net/http使用c-ares而不是getaddrinfo()
EN

Stack Overflow用户
提问于 2013-10-04 15:27:00
回答 1查看 698关注 0票数 6

正如文档所说:

除了在线程池中使用getaddrinfo(3)的dns.lookup之外,dns模块中的所有方法都使用C。

然而,net和http模块总是使用dns.lookup。有办法改变这种情况吗?getaddrinfo是同步的,池只允许4个并发请求。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-12-12 11:08:10

在对此进行研究之后,似乎唯一的方法是手动执行DNS请求。我用这样的方法:

代码语言:javascript
复制
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();
  });
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19185055

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档