使用 Node JS 检查多个网站状态

Multiple Website Status Check with Node JS

我想要 运行 一个可以检查多个网站并以正确的状态代码响应的节点应用程序。我正在使用 Node 本身的 'request' 模块。

我的代码是:

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

这适用于一个网站。但是,我想知道如何 运行 为多个站点提供相同的功能?例如,url 应该来自 urls 的数组。

如果我有一个 url 数组,例如:

var urls = ["https://www.google.com", "https://www.yahoo.com"];

如何将这些单独的 url 提供给请求函数?并获得每个站点的结果?

你可以用一个承诺列表来做到这一点,应该很容易做到:

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