检查是否联网的一个脚本
js
// main.js
const ping = require('ping');
const username = 'lukecheng'
const password = 'WCiam1670@com%125'
const time = 1000;
let timer = null;
let requestCount = 0
/**
* 启动一个定时器,调用监听函数,并再次执行自己
*/
function start () {
timer = setTimeout(async () => {
await watchInternet();
start();
}, time);
}
/**
* 调用系统 ping 命令,检测电脑是否联网
*/
async function isOnline () {
const { alive } = await ping.promise.probe('www.baidu.com');
return alive;
}
/**
* 监听网络状态,如果断网,则调用 login 函数
*/
async function watchInternet () {
requestCount ++
const online = await isOnline();
console.error('是否联网' + requestCount, online);
if (!online) {
try {
console.log('\x1b[33m%s\x1b[0m', '网络断开,尝试重新登录...');
await login();
} catch (error) {
console.log('\x1b[31m%s\x1b[0m', '登录失败,正在重试...');
}
}
}
/**
* 登录函数
*/
async function login () {
console.log('登录成功')
}
start();