实用的端口检测模块detect-port
特点
- 可检测socket端口
- 无其他模块依赖
- 较全面的单测覆盖
- npm下载量、使用量高
- 集成了命令行工具
相关链接
github: https://github.com/xudafeng/detect-port npm: https://www.npmjs.com/package/detect-port
支持多种异步使用方式
Usage
$ npm i detect-port --save
const detect = require('detect-port');
/**
* callback usage
*/
detect(port, (err, _port) => {
if (err) {
console.log(err);
}
if (port === _port) {
console.log(`port: ${port} was not occupied`);
} else {
console.log(`port: ${port} was occupied, try port: ${_port}`);
}
});
/**
* for a yield syntax instead of callback function implement
*/
const co = require('co');
co(function *() {
const _port = yield detect(port);
if (port === _port) {
console.log(`port: ${port} was not occupied`);
} else {
console.log(`port: ${port} was occupied, try port: ${_port}`);
}
});
/**
* use as a promise
*/
detect(port)
.then(_port => {
if (port === _port) {
console.log(`port: ${port} was not occupied`);
} else {
console.log(`port: ${port} was occupied, try port: ${_port}`);
}
})
.catch(err => {
console.log(err);
});
Command Line Tool
$ npm i detect-port -g
Quick Start
# get an available port randomly
$ detect
# detect pointed port
$ detect 80
# more help
$ detect --help
7 回复
如果能把readme放上来的就更好了
@i5ting 好的
@xudafeng 棒棒哒,是给egg用的把
@i5ting 不是专门给哪里用的,谁都可以用,哈哈
这种通过 server.listen
来检测可用端口的事情,以前在某个【获取随机可用端口】的场景下见过。
类似这样的,不知这种 freePort 端口获取适不适合加入你这个包:
var net = require('net');
var srv = net.createServer(function(sock) {
sock.end('Hello world\n');
});
srv.listen(0, function() {
console.log('Listening on port ' + srv.address().port);
});
@alsotang 现在随机端口功能有的,是在外围实现的 https://github.com/xudafeng/detect-port/blob/master/bin/detect-port#L32
@xudafeng 我没有注意看代码。只是我看 readme 里面的 api 说明,只说了 detect-port 作为 lib 使用时,接收一个 port 的情况,没有给出不传入 port 的示例。