CNode

实用的端口检测模块detect-port

分享
Xxudafeng发布于10 年前最后回复9 年前9 回复10155 浏览0 收藏

特点

  • 可检测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
查看回复

回复 (9)

I
i5ting#1·10 年前

如果能把readme放上来的就更好了

I
i5ting#3·10 年前
引用 xudafeng@i5ting 好的

@xudafeng 棒棒哒,是给egg用的把

X
xudafeng#4·10 年前
引用 i5ting@xudafeng 棒棒哒,是给egg用的把

@i5ting 不是专门给哪里用的,谁都可以用,哈哈

A
alsotang#5·10 年前

这种通过 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);
});
X
xudafeng#6·10 年前

@alsotang 现在随机端口功能有的,是在外围实现的 https://github.com/xudafeng/detect-port/blob/master/bin/detect-port#L32

A
alsotang#7·10 年前
引用 xudafeng@alsotang 现在随机端口功能有的,是在外围实现的 https://github.com/xudafeng/detect port/blob/master/bin/detect port...

@xudafeng 我没有注意看代码。只是我看 readme 里面的 api 说明,只说了 detect-port 作为 lib 使用时,接收一个 port 的情况,没有给出不传入 port 的示例。

X
xudafeng#8·9 年前
A
atian25#9·9 年前

👍👍👍👍👍👍👍 image.png

参与回复
登录后即可参与回复。登录