检查 NodeJs 中的互联网连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15270902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check for internet connectivity in NodeJs
提问by Donald Derek
Installed NodeJS on Raspberry Pi, is there a way to check if the rPi is connected to the internet via NodeJs ?
在 Raspberry Pi 上安装了 NodeJS,有没有办法检查 rPi 是否通过 NodeJs 连接到互联网?
回答by Jaruba
While robertklep's solution works, it is far from being the best choice for this. It takes about 3 minutes for dns.resolveto timeout and give an error if you don't have an internet connection, while dns.lookupresponds almost instantly with the error ENOTFOUND.
虽然 robertklep 的解决方案有效,但它远不是最好的选择。dns.resolve如果您没有互联网连接,超时并给出错误大约需要 3 分钟,而dns.lookup几乎立即响应错误ENOTFOUND。
So I made this function:
所以我做了这个功能:
function checkInternet(cb) {
require('dns').lookup('google.com',function(err) {
if (err && err.code == "ENOTFOUND") {
cb(false);
} else {
cb(true);
}
})
}
// example usage:
checkInternet(function(isConnected) {
if (isConnected) {
// connected to the internet
} else {
// not connected to the internet
}
});
This is by far the fastest way of checking for internet connectivity and it avoids all errors that are not related to internet connectivity.
这是迄今为止检查互联网连接的最快方法,它避免了与互联网连接无关的所有错误。
回答by robertklep
A quick and dirty way is to check if Node can resolve www.google.com:
一种快速而肮脏的方法是检查 Node 是否可以解析www.google.com:
require('dns').resolve('www.google.com', function(err) {
if (err) {
console.log("No connection");
} else {
console.log("Connected");
}
});
This isn't entire foolproof, since your RaspPi can be connected to the Internet yet unable to resolve www.google.comfor some reason, and you might also want to check err.typeto distinguish between 'unable to resolve' and 'cannot connect to a nameserver so the connection might be down').
这并非完全万无一失,因为您的 RaspPi 可以连接到 Internet 但由于www.google.com某种原因无法解析,并且您可能还需要检查err.type以区分“无法解析”和“无法连接到名称服务器,因此连接可能下来')。
回答by Kristian Evensen
I had to build something similar in a NodeJS-app some time ago. The way I did it was to first use the networkInterfaces()function is the OS-module and then check if one or more interfaces have a non-internal IP.
前段时间我不得不在 NodeJS 应用程序中构建类似的东西。我这样做的方法是首先使用networkInterfaces()函数是操作系统模块,然后检查一个或多个接口是否具有非内部 IP。
If that was true, then I used exec()to start ping with a well-defined server (I like Google's DNS servers). By checking the return value of exec(), I know if ping was sucessful or not. I adjusted the number of pings based on the interface type. Forking a process introduces some overhead, but since this test is not performed too frequently in my app, I can afford it. Also, by using ping and IP-adresses, you dont depend on DNS being configured. Here is an example:
如果这是真的,那么我使用exec()开始 ping 一个定义良好的服务器(我喜欢 Google 的 DNS 服务器)。通过检查 exec() 的返回值,我知道 ping 是否成功。我根据接口类型调整了ping次数。分叉进程会带来一些开销,但由于此测试在我的应用程序中执行的频率不高,因此我可以负担得起。此外,通过使用 ping 和 IP 地址,您不依赖于配置的 DNS。下面是一个例子:
var exec = require('child_process').exec, child;
child = exec('ping -c 1 128.39.36.96', function(error, stdout, stderr){
if(error !== null)
console.log("Not available")
else
console.log("Available")
});
回答by Caio Wilson
It's not as foolproof as possible but get the job done:
它不是尽可能万无一失,但可以完成工作:
var dns = require('dns');
dns.lookupService('8.8.8.8', 53, function(err, hostname, service){
console.log(hostname, service);
// google-public-dns-a.google.com domain
});
just use a simple if(err)and treat the response adequately. :)
只需使用简单if(err)并充分处理响应即可。:)
ps.: Please don't bother telling me 8.8.8.8 is not a name to be resolved, it's just a lookup for a highly available dns server from google. The intention is to check connectivity, not name resolution.
ps.:请不要告诉我 8.8.8.8 不是要解析的名称,它只是从 google 查找高度可用的 dns 服务器。目的是检查连接性,而不是名称解析。
回答by Freddy Daniel
I found a great and simple npm tool to detect internet connection. It's looks like more reliable.
我找到了一个伟大而简单的 npm 工具来检测互联网连接。看起来比较靠谱。
First you need to install
npm i check-internet-connected
首先你需要安装
npm i check-internet-connected
Then you can call it like follows
然后你可以像下面这样调用它
const checkInternetConnected = require('check-internet-connected');
const config = {
timeout: 5000, //timeout connecting to each server(A and AAAA), each try (default 5000)
retries: 5,//number of retries to do before failing (default 5)
domain: 'google.com'//the domain to check DNS record of
}
checkInternetConnected(config)
.then(() => {
console.log("Internet available");
}).catch((error) => {
console.log("No internet", error);
});
回答by Roman Frolov
As of 2019 you can use DNS promises lookup.
截至 2019 年,您可以使用DNS 承诺查找。
NOTEThis API is experimental.
注意此 API 是实验性的。
const dns = require('dns').promises;
exports.checkInternet = function checkInternet() {
return dns.lookup('google.com')
.then(() => true)
.catch(() => false);
};
回答by Javad
Since I was concerned with DNS cache in other solutions here, I tried an actual connectivity test using http2. I think this is the best way to test the internet connection as it doesn't send much data and also doesn't rely on DNS resolving alone and it is quite fast.
由于我担心这里其他解决方案中的 DNS 缓存,因此我尝试使用 http2 进行实际连接测试。我认为这是测试互联网连接的最佳方式,因为它不会发送太多数据,也不依赖于单独的 DNS 解析,而且速度非常快。
Note that this was added in: v8.4.0
const http2 = require('http2');
function isConnected() {
return new Promise((resolve) => {
const client = http2.connect('https://www.google.com');
client.on('connect', () => {
resolve(true);
client.destroy();
});
client.on('error', () => {
resolve(false);
client.destroy();
});
});
};
isConnected().then(console.log);
Edit: I made this into a packageif anyone is interested.
编辑:如果有人感兴趣,我把它做成了一个包。
回答by Nagnath Mungade
It is very helpful to check internet connection for our browser is available or not.
检查我们的浏览器的互联网连接是否可用非常有帮助。
var internetAvailable = require("internet-available");
internetAvailable().then(function(){
console.log("Internet available",internetAvailable);
}).catch(function(){
console.log("No internet");
});
for more[internet-available][1]: https://www.npmjs.com/package/internet-available
更多[互联网可用][1]:https: //www.npmjs.com/package/internet-available

