使用 Node.js 测试网址

Testing URLs with Node.js

本文关键字:测试 js Node 使用      更新时间:2023-09-26

>假设我有一个 URL 数组,并且我想确保每个 URL 都正常工作,我创建了以下代码。 但是,仅测试数组中的最后一个 URL。 如何确保每个 url 返回 200 响应代码? 需要明确的是,这些都是我正在测试的远程地址,它们指向大小适中的 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]; 重写 l 变量

所以 l 的值是数组的最后一个值。为了保留唯一的l值,您需要将其存储在某个地方。更好 - 功能。喜欢这个:

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);
}

在这里,拥有函数不是魔法。它只是在每次函数调用的内存中保留本地值,因此每次需要 l 时都是唯一的。

for表达式不应与数组一起使用。将 for 循环替换为如下所示的内容:

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

执行这么多传出请求时,您可能希望将maxSockets增加到大于默认值 5 的值,否则可能会遇到意外行为。在require('http')后执行此操作:

http.globalAgent.maxSockets = 150;

此外,当您将console.log放在回调函数之外时,它不会在从服务器返回响应的同时显示。反正这是多余的。这是一个完整的工作示例:

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);
});