检查 NodeJs 中的互联网连接 [英] Check for internet connectivity in NodeJs

查看:50
本文介绍了检查 NodeJs 中的互联网连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在树莓派上安装了 NodeJS,有没有办法检查 rPi 是否通过 NodeJs 连接到互联网?

Installed NodeJS on Raspberry Pi, is there a way to check if the rPi is connected to the internet via NodeJs ?

推荐答案

一个快速而肮脏的方法是检查 Node 是否可以解析 www.google.com:

A quick and dirty way is to check if Node can resolve www.google.com:

require('dns').resolve('www.google.com', function(err) {
  if (err) {
     console.log("No connection");
  } else {
     console.log("Connected");
  }
});

这并非完全万无一失,因为您的 RaspPi 可以连接到 Internet 但由于某种原因无法解析 www.google.com,您可能还想检查 err.type 以区分无法解析"和无法连接到名称服务器,因此连接可能已关闭").

This isn't entire foolproof, since your RaspPi can be connected to the Internet yet unable to resolve www.google.com for some reason, and you might also want to check err.type to distinguish between 'unable to resolve' and 'cannot connect to a nameserver so the connection might be down').

这篇关于检查 NodeJs 中的互联网连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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