所以我们要将大量内容从一个站点移动到另一个站点,所有内容都会有不同的路径。网络服务器将使用 301 重定向来确保拥有现有书签的人可以访问新资源。我被要求编写一个脚本来测试所有重定向是否已正确设置。
预期的重定向将在具有以下格式的文本文件中:
/path/to/resource/1 http://www.newsite.com/new/path/to/resource1
/path/to/resource/2 http://www.newsite.com/new/path/to/resource2
这将是一个非常大的文件,所以我编写了一个 Node 脚本,它使用 line-reader
从文件中提取每一行,并将其传递给一个函数来进行实际检查。
它适用于长达五行的文件。如果文件有超过 5 个条目,它仍然循环遍历整个文件并且每次都调用检查函数(我使用 console.log 来确认这一点)但只有前五个返回——下面的代码列出了“为文件中的每一行调用 check301 for...”,但只有前五行命中了“Getting...”日志语句。我试过增加超时。我检查 http get 调用上的错误。我添加了代码试图捕获任何未处理的异常。纳达。
我错过了什么?
编辑:显然我缺少的是 http 默认为一次可用的五个套接字 ( http://nodejs.org/api/http.html#http_agent_maxsockets ) 并且我的服务器正在发送保持事件状态。有没有办法强制连接忽略 keep-alive header ,或者在我处理完响应后销毁连接?
/* 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
(我建议仅针对您的特定情况,但不是默认情况转到选项):http://nodejs.org/api/http.html#http_http_request_options_callback
IIRC,未使用 Node.js HTTP's underlying default Agent还将减轻您正在观察的汇集“问题”。
额外信息:像您通过间隔所做的那样,简单地将请求数量限制为 5 个/秒是不够的。在开始下一个之前,您需要等待 http.get
调用回调。在捕获响应和关闭连接的时间超过 1 秒的情况下,您的请求速率将超过每秒 5 个。我推荐类似于异步的并行限制控制流程的东西:https://github.com/caolan/async#parallellimittasks-limit-callback
关于node.js - Node : close http. 即使服务器发送保持事件状态也得到响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24686929/