How to detect network changes using Node.js

后端 未结 1 1227
别那么骄傲
别那么骄傲 2021-02-10 00:02

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 simil

相关标签:
1条回答
  • 2021-02-10 00:04

    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!');
    });
    
    0 讨论(0)
提交回复
热议问题