我想运行一个节点应用程序,该应用程序将检查多个网站并以正确的状态代码进行响应。我正在使用Node本身的“请求”模块。
我的代码是:
const request = require('request')
function getStatus() {
request('https://www.google.com', function(error, response, body) {
result = response.statusCode;
if(!error && response.statusCode == 200) {
document.write("The Site Is Up");
console.log(result);
} else {
console.log("The Site Is Down");
}
});
}
这对于一个网站正常工作。但是,我想知道如何为多个站点运行相同的功能?例如,应从一组网址中获取该网址。
如果我有一个网址数组,例如:
var urls = ["https://www.google.com", "https://www.yahoo.com"];
如何将这些单独的网址提供给请求函数?并获得每个网站的结果?
答案 0 :(得分:0)
您可以使用承诺列表来做到这一点,应该很容易做到:
const request = require('request')
const urlList = ["https://www.google.com", "https://www.amazon.com"];
function getStatus(url) {
return new Promise((resolve, reject) => {
request(url, function(error, response, body) {
resolve({site: url, status: (!error && response.statusCode == 200) ? "OK": "Down: " + error.message});
});
})
}
let promiseList = urlList.map(url => getStatus(url));
Promise.all(promiseList).then(resultList => {
resultList.forEach(result => console.log("Result: ", result));
});
您还可以使用我们的request-promise-native库获得更好的API:
const request = require('request')
const rp = require('request-promise-native')
const urlList = ["https://www.google.com", "https://www.amazon.com", "https://doesnotexist.none", "https://wikipedia.org"];
function getStatusRp(url) {
return rp({uri: url, resolveWithFullResponse: true }).then((response) => {
return { site: url, status: response.statusCode === 200 ? "OK": "Down"};
}, (err) => {
return { site: url, status: "Down: " + err.message};
});
}
let promiseList = urlList.map(url => getStatusRp(url));
Promise.all(promiseList).then(resultList => {
resultList.forEach(result => console.log("Result: ", result));
});