使用Node.jstestingURL

假设我有一个URL数组,我想确保每个URL都可以工作,我已经创build了下面的代码。 但是只有数组中的最后一个URL正在testing。 我怎样才能确保每个url返回200响应代码? 要清楚这些都是我正在testing的所有远程地址,他们指向体面大小的PDF。

根据@ lukas.pukenis的回复进行更新。 结果是相似的,实际上只检查了几个文件。

function check(l) { console.log(l); http.get(l, function(res) { if (res.statusCode != 200) { console.log(res.statusCode + ' on '+l); } else { console.log('success on ' + l); } }); } for (link in fileLinks) { check(fileLinks[link]); } 

这个代码输出:

 http://somesite.com/somefile1.pdf http://somesite.com/somefile2.pdf http://somesite.com/somefile3.pdf ... all the rest of them ... http://somesite.com/somefile99.pdf success on http://somesite.com/somefile1.pdf success on http://somesite.com/somefile2.pdf 404 on http://somesite.com/somefile5.pdf success on http://somesite.com/somefile7.pdf 

这是因为你的循环每次用var l = fileLinks[link];重写lvariablesvar l = fileLinks[link];

所以我有一个数组的最后一个值的值。 为了保存唯一的值,你需要把它存储在某个地方。 更好 – function。 喜欢这个:

 function check(l) { var req = http.get(l, function(res) { if (res.statusCode != 200) { console.log(res.statusCode + ' on '+l); } else { console.log('success on ' + l); } } req.on('close', function() { console.log('Request done'); }); for (link in fileLinks) { var l = fileLinks[link]; check(l); } 

有一个function在这里没有什么魔力。 它只是在每个函数调用的内存中保留你的本地值,所以每次需要时l都是唯一的。

forexpression式不应该与数组一起使用。 replace为这样的for循环:

 fileLinks.forEach(function(item){ check(item); }); 

当做这许多传出的请求,你可能想要增加maxSockets大于5, 默认 ,否则你可能会得到意想不到的行为。 在你require('http')后做这个:

 http.globalAgent.maxSockets = 150; 

另外,当你将console.log放在callback函数之外时,它不会在响应从服务器返回的同时显示出来。 无论如何,这是多余的。 这是一个完整的工作示例:

 var http = require('http'); var url = require('url'); function check(l) { var u = url.parse(l); var opts = { host: u.host, path: u.path, agent: false // prevents pooling behavior }; http.get(opts, function(res) { if (res.statusCode != 200) { console.log(res.statusCode + ' on '+l); } else { console.log('success on ' + l); } }); } fileLinks = ['http://www.google.com','http://www.google.com']; fileLinks.forEach(function(item){ check(item); });