Node.js函数检查网站是否正常运行 [英] Nodejs function to check if website is working

查看:58
本文介绍了Node.js函数检查网站是否正常运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数来检查给定的URL是否正常工作.这是我到目前为止所做的:

I'm trying to make a function that checks if the given URL is working or not. This is what I've done so far:

function checkWebsite(url) {
  http
    .get(url, function(res) {
      console.log(url, res.statusCode);
      return res.statusCode === 200;
    })
    .on("error", function(e) {
      return false;
    });
}

我想等到http get完成,然后根据状态码返回true或false,并且作为回调函数中的响应,我不知道如何将其返回到调用它的位置.示例调用:

I want to wait until http get is finished and then return true or false based on the status code and being the response in a callback function I don't know how to return it back to where it was called. Example call:

function test() {
   if (checkWebsite("https://stackoverflow.com/")) {
    return "https://stackoverflow.com/";
   } 
}

我想在此if语句中获得true或false,但是由于状态代码位于回调函数中,因此我不知道如何返回它.

I want to get the true or false in this if statement but since the status code is in a callback function I don't know how to return it.

推荐答案

我将为您提供一个有效的代码段,因为您无法从链接的答案中找出答案,也许会对您有所帮助:

I'll give you a working snippet since you cannot figure it out from the linked answer, maybe it'll help you more:

var http = require('http');
var https = require('https');

test();

function checkWebsite(url, callback) {
  https
    .get(url, function(res) {
      console.log(url, res.statusCode);
      return callback(res.statusCode === 200);
    })
    .on("error", function(e) {
      return callback(false);
    });
}

function test(){
    checkWebsite("https://stackoverflow.com/", function(check){
        console.log(check); //true
    })
}

有诺言:

var http = require('http');
var https = require('https');

test();

function checkWebsite(url) {
    return new Promise((resolve, reject) => {
      https
        .get(url, function(res) {
          console.log(url, res.statusCode);
          resolve(res.statusCode === 200);
        })
        .on("error", function(e) {
          resolve(false);
        });     
    })
}
async function test(){
    var check = await checkWebsite("https://stackoverflow.com/");
    console.log(check); //true
}

这篇关于Node.js函数检查网站是否正常运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆