我查看了 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/