这是我解决这个问题的方法:
const IsPortReachable = require('is-port-reachable');
var options = {
start_port : 2994,
end_port : 3003,
findFirstFree : true
}
function CheckPort(port, firstFree, callback) {
IsPortReachable(port, {host: 'localhost'})
.then((reachable) => {
if (reachable) {
console.log(port, "reachable");
if (firstFree) callback(port);
}
else {
console.log(port, "free")
if (!firstFree) callback(port);
}
})
}
function CheckPortHandler(port, firstFree) {
if (port >= options.end_port) return;
CheckPort(port + 1, firstFree, CheckPortHandler)
}
CheckPort(options.start_port, options.findFirstFree, CheckPortHandler);
您可以在选项中更改开始和结束端口。如果要查找第一个可到达的端口(与第一个可用端口相反),请更改
findFirstFree
到
false
.
在代码中,我正在创建一个函数
CheckPort
它绕着
IsPortReachable
但也会收到一个回调。如果
reachable
状态不符合
firstFree
参数。回调是另一个调用
检查口
同样,使用一个递增的端口,因此该过程将继续。它一直持续到
可达成的
状态与
第一免费
参数,因此不再调用回调。
可能有点混乱,但对我来说没问题。
这里是输出
findFirstFree : true
2994 'free'
findFirstFree : false
2994 'free'
2995 'free'
2996 'free'
2997 'free'
2998 'free'
2999 'free'
3000 'reachable'