Check for internet connectivity in NodeJs

后端 未结 10 1747
甜味超标
甜味超标 2020-12-08 07:10

Installed NodeJS on Raspberry Pi, is there a way to check if the rPi is connected to the internet via NodeJs ?

10条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-08 07:19

    I had to build something similar in a NodeJS-app some time ago. The way I did it was to first use the networkInterfaces() function is the OS-module and then check if one or more interfaces have a non-internal IP.

    If that was true, then I used exec() to start ping with a well-defined server (I like Google's DNS servers). By checking the return value of exec(), I know if ping was sucessful or not. I adjusted the number of pings based on the interface type. Forking a process introduces some overhead, but since this test is not performed too frequently in my app, I can afford it. Also, by using ping and IP-adresses, you dont depend on DNS being configured. Here is an example:

    var exec = require('child_process').exec, child;
    child = exec('ping -c 1 128.39.36.96', function(error, stdout, stderr){
         if(error !== null)
              console.log("Not available")
          else
              console.log("Available")
    });
    

提交回复
热议问题