Reputation: 384
How can I listen for changes in the network connectivity?
Do you know any implementation or module that accomplish this?
I'm wondering if exists something similar to:
reachability.on('change' function(){...});
reachability.on('connect' function(){...});
reachability.on('disconnect' function(){...});
I've googled it and couldn't find anything about it.
Any help is appreciated. Thank you
Upvotes: 5
Views: 5753
Reputation: 135
It's an old question, but I found use ip
npm package should work. You can just setInterval
to use ip.address()
to check your machine ip address is wether changed or not.
Upvotes: 0
Reputation: 106696
There is no such functionality built-in to node. You might be able to hook into the OS to listen for the network interface going up or down or even an ethernet cable being unplugged, but any other type of connectivity loss is going to be difficult to determine instantly.
The easiest way to detect dead connections is to use an application-level ping/heartbeat mechanism and/or a timeout of some kind.
If the network connectivity detection is not specific to a particular network request, you could do something like this to globally test network connectivity by continually pinging some well-connected system that responds to pings. Example:
var EventEmitter = require('events').EventEmitter,
spawn = require('child_process').spawn,
rl = require('readline');
var RE_SUCCESS = /bytes from/i,
INTERVAL = 2, // in seconds
IP = '8.8.8.8';
var proc = spawn('ping', ['-v', '-n', '-i', INTERVAL, IP]),
rli = rl.createInterface(proc.stdout, proc.stdin),
network = new EventEmitter();
network.online = false;
rli.on('line', function(str) {
if (RE_SUCCESS.test(str)) {
if (!network.online) {
network.online = true;
network.emit('online');
}
} else if (network.online) {
network.online = false;
network.emit('offline');
}
});
// then just listen for the `online` and `offline` events ...
network.on('online', function() {
console.log('online!');
}).on('offline', function() {
console.log('offline!');
});
Upvotes: 6