Javascript 是否有一种节点方式来检测网络接口是否联机?

Javascript 是否有一种节点方式来检测网络接口是否联机?,javascript,node.js,Javascript,Node.js,我已经看过了操作系统模块和ip模块,但它们非常擅长告诉我系统的当前ip地址,而不是新模块是否在线或离线。我知道我可以使用udev规则来解决这个问题(我在Ubuntu上),但我希望有一种只使用node的方法来解决这个问题。如何查找网络接口是否已启动?您始终可以使用设置侦听器,并查看自上次以来接口集是否已更改。如果是,请将更新发送给任何侦听器 'use strict'; let os = require('os'); // Track the listeners and provide a wa

我已经看过了操作系统模块和ip模块,但它们非常擅长告诉我系统的当前ip地址,而不是新模块是否在线或离线。我知道我可以使用udev规则来解决这个问题(我在Ubuntu上),但我希望有一种只使用node的方法来解决这个问题。如何查找网络接口是否已启动?

您始终可以使用设置侦听器,并查看自上次以来接口集是否已更改。如果是,请将更新发送给任何侦听器

'use strict';

let os = require('os');

// Track the listeners and provide a way of adding a new one
// You would probably want to put this into some kind of module
// so it can be used in various places
let listeners = [];
function onChange(f) {
    if (listeners.indexOf(f) === -1) {
        listeners.push(f);
    }
}

let oldInterfaces = [];
process.nextTick(function checkInterfaces() {
    let interfaces = os.networkInterfaces();

    // Quick and dirty way of checking for differences
    // Not very efficient
    if (JSON.stringify(interfaces) !== JSON.stringify(oldInterfaces)) {
        listeners.forEach((f) => f(interfaces));
        oldInterfaces = interfaces;
    }

    // Continue to check again on the next tick
    process.nextTick(checkInterfaces);
});

// Print out the current interfaces whenever there's a change
onChange(console.log.bind(console));

不幸的是,在节点中没有基于事件的方法来实现这一点。我们提出的解决方案是使用UDEV在设备脱机和联机时生成事件