Check for internet connectivity in NodeJs

后端 未结 10 1742
甜味超标
甜味超标 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:32

    Since I was concerned with DNS cache in other solutions here, I tried an actual connectivity test using http2. I think this is the best way to test the internet connection as it doesn't send much data and also doesn't rely on DNS resolving alone and it is quite fast.

    Note that this was added in: v8.4.0

    const http2 = require('http2');
    
    function isConnected() {
      return new Promise((resolve) => {
        const client = http2.connect('https://www.google.com');
        client.on('connect', () => {
          resolve(true);
          client.destroy();
        });
        client.on('error', () => {
          resolve(false);
          client.destroy();
        });
      });
    };
    
    isConnected().then(console.log);
    

    Edit: I made this into a package if anyone is interested.

提交回复
热议问题