简体   繁体   中英

How to detect network changes using Node.js

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

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!');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM