javascript - 是否有 Node 方法来检测网络接口(interface)是否联机?

标签 javascript node.js

我查看了 os 模块和 ip 模块,但它们真的很擅长告诉我系统的当前 ip 地址,而不是新的上线或下线。我知道我可以使用 udev 规则(我在 Ubuntu 上)来解决这个问题,但我希望有一种方法可以只使用 Node 来解决这个问题。我将如何发现网络接口(interface)是否已启动?

最佳答案

您始终可以使用 process.nextTick 设置监听器并查看自上次以来接口(interface)集是否发生了变化。如果是这样,请将更新发送给任何听众。

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

关于javascript - 是否有 Node 方法来检测网络接口(interface)是否联机?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37666669/

相关文章:

javascript - 链接在 Bootstrap 导航栏中不起作用的菜单项

node.js - 如何使用 "Non Atomic"批处理/管道在 Scylla 中运行多个查询

node.js - 使用 NODEJS 将 POST 请求正文发送到网页

javascript - PHP页面: Dropdown always selects the first value

javascript - 有没有办法创建变量的名称并从循环中进行更改?

javascript - 如何在 promise 的 then 回调中设置 `this` 的上下文

angularjs - 如何根据 Nodejs 中的环境变量在 Angular 中插入动态脚本

node.js - fluent-ffmpeg:使用流将 wav 转换为 alac .m4a

javascript - 我如何编写一个函数,如果它的参数是一个 Node 集合,则对 javascript 中的所有 Node 元素执行?

javascript - 了解 css 类如何更改/更新