Node:即使服务器发送保持活动状态,closureshttp.get响应

所以我们要将大量的内容从一个站点移动到另一个站点,而所有的内容将有不同的path。 networking服务器将使用301redirect来确保具有现有书签的人员获得新资源。 我被要求写一个脚本来testing所有的redirect已经正确设置。

预期的redirect将使用以下格式的文本文件:

/path/to/resource/1 http://www.newsite.com/new/path/to/resource1 /path/to/resource/2 http://www.newsite.com/new/path/to/resource2 

这将是一个非常大的文件,所以我编写了一个节点脚本,它使用line-reader将每行拉出文件,并将其传递给执行实际检查的函数。

它适用于最多五行的文件。 如果文件有5个以上的条目,它仍然遍历整个文件,它每次调用检查函数(我已经使用console.log来确认这一点),但只有前五个返回 – 下面的代码列出了“为文件中的每一行调用check301 …“,但只有前五个命中”获取…“日志语句。 我试过增加超时。 我检查在http获取调用的错误。 我添加了代码,试图捕获任何未处理的exception。 纳达。

我错过了什么?

编辑︰所以显然我所缺less的是,http默认一次可用五个套接字( http://nodejs.org/api/http.html#http_agent_maxsockets )和我的服务器发送保持活动。 有没有办法强制连接忽略保持活动头,或一旦我完成处理响应销毁连接?

 /* Check a provided list of URL pairs for redirection. * redirects.txt should have one line per redirect, with the url to * be requested and the URL to be redirected to seperated by a space. */ var urlBase = "http://www.example.com", testPair = [], http = require('http'), lineReader = require('line-reader'); function check301(source, destination){ console.log('Calling check301 for ' + source); var target = urlBase + source; http.get(target, function(response){ console.log('Getting ' + source); if (response.statusCode != 301 || response.headers.location != destination){ console.log(source + ' does not redirect to ' + destination); } }).on('error', function(e){ console.log(e.message); }); } //Throttled version. No more than 5 reqs a second to keep the server happy. lineReader.open('redirects.txt', function(reader){ var interval = setInterval(function(){ if(reader.hasNextLine()){ reader.nextLine(function(line){ testPair = line.split(' '); check301(testPair[0], testPair[1]); }); } else { clearInterval(interval); console.log('Done'); } }, 200); }); 

agent属性设置为false以强制Connection: close (我build议这只适用于您的具体情况,而不是作为默认的前往选项): http : //nodejs.org/api/http.html#http_http_request_options_callback

IIRC,不使用Node.js HTTP的底层默认代理也将缓解您正在观察的池“问题”。

奖励信息:只需将请求数量限制为5 /秒,就像您通过间隔完成的那样不够好。 你需要等待你的http.get调用callback,然后再开始下一个。 在需要超过1秒的时间捕获响应并closures连接的情况下,您的请求速率将超过每秒5次。 我推荐类似于asynchronous的并行限制控制stream程: https : //github.com/caolan/async#parallellimittasks-limit-callback