我正在尝试检测node.js和电子设备中的Internet连接。
我的代码每1秒钟通知一次互联网连接。
但是我想要的是在连接,断开连接时显示连接性 (仅在切换连接时),而不是每隔1秒钟。
我可以在node.js和电子中做到这一点吗?
main.js
const dns = require('dns');
function liveCheck() {
dns.resolve('www.google.com', function(err, addr){
if (err) {
notifier.notify(
{
appName: "com.myapp.id",
title: "network error",
message: "disconnected",
icon:"./facebook.png"
}
);
}
else{
console.log("connected");
}
});
}
setInterval(function() {
liveCheck()
},1000);
答案 0 :(得分:2)
如果要保持相同的逻辑,则需要添加一个标志,以查看是否从无连接切换为已连接。我是通过isConnected
完成的
标记:
const dns = require("dns");
let isConnected = false;
function liveCheck() {
dns.resolve("www.google.com", function(err, addr) {
if (err) {
if (isConnected) {
notifier.notify({
appName: "com.myapp.id",
title: "network error",
message: "disconnected",
icon: "./facebook.png",
});
}
isConnected = false;
} else {
if (isConnected) {
//connection is still up and running, do nothing
} else {
notifier.notify({
appName: "com.myapp.id",
title: "connection gained",
message: "connected",
icon: "./facebook.png",
});
}
isConnected = true;
}
});
}
setInterval(function() {
liveCheck();
}, 1000);
答案 1 :(得分:2)
npm install internet-available
var internetAvailable = require("internet-available");
// Set a timeout and a limit of attempts to check for connection
internetAvailable({
timeout: 4000,
retries: 10,
}).then(function(){
console.log("Internet available");
}).catch(function(){
console.log("No internet");
});
答案 2 :(得分:1)
navigator.onLine是不可靠的方法。所以我发现npm util可以处理这种情况
安装npm i check-internet-connected
并使用它
const checkInternetConnected = require('check-internet-connected');
const config = {
timeout: 5000, //timeout connecting to each try (default 5000)
retries: 3,//number of retries to do before failing (default 5)
domain: 'apple.com'//the domain to check DNS record of
}
checkInternetConnected(config)
.then(() => {
console.log("Connection available");
}).catch((err) => {
console.log("No connection", err);
});