检查NodeJ中的Internet连接 [英] Check for internet connectivity in NodeJs

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

问题描述

在Raspberry Pi上安装了NodeJS,是否可以检查rPi是否通过NodeJs连接到Internet?

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').

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

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