Macaca [推荐] 实用的端口探测工具 detect-port 升级 (v0.1.4)

鹤见 · 2015年08月25日 · 最后由 鹤见 回复于 2015年08月25日 · 1829 次阅读

端口探测工具介绍

之前介绍的端口探测工具版本更新了,现在支持更多实用的用法。

升级特性

  • 支持 TCP 占用检测。
  • 支持 Promise 接口。

使用场景

  • 命令行执行(多平台,windows,mac 以及 linux)
  • 作为 node.js 的模块引入。

安装环境

  • node.js(io.js) 版本>= 0.12 均可支持,推荐从iojs 官网下载。
  • 下载完成后命令行执行 npm i detect-port -g 即可。

用法

1、命令行

# detect port 80
$ detect -p 80

# or like this
$ detect --port 80

# will get result below
$ port: 80 was occupied, try port: 1024

# with verbose
$ detect --port 80 --verbose

# more help?
$ detect -h

2、node.js 代码,当做第三方模块引入,支持多种异步调用方式(回调、co 迭代器、promise)。

var detect = require('detect-port');

/**
 * 普通用法
 */

detect(port, function(error, _port) {
  if (error) {
    console.log('Error');
    return;
  }
  if (port === _port) {
    console.log('port: %d was not occupied', port);
  } else {
    console.log('port: %d was occupied, try port: %d', port, _port);
  }
});

/**
 * 在co v3中使用 
 * for a yield syntax instead of callback function implement
 */

var co = require('co');

co(function *() {
  var _port = yield detect(port);

  if (port === _port) {
    console.log('port: %d was not occupied', port);
  } else {
    console.log('port: %d was occupied, try port: %d', port, _port);
  }
})();

/**
 * 在co v4中使用 
 * for a yield syntax instead of callback function implement
 */

var co = require('co');

co(function *() {
  var _port = yield detect(port);

  if (port === _port) {
    console.log('port: %d was not occupied', port);
  } else {
    console.log('port: %d was occupied, try port: %d', port, _port);
  }
});

/**
 * 作为 promise 使用
 */

var promisePort = detect(port);

promisePort.then(function(_port) {
  if (port === _port) {
    console.log('port: %d was not occupied', port);
  } else {
    console.log('port: %d was occupied, try port: %d', port, _port);
  }
}).catch(function(err) {
    console.log(err);
});

更多

项目托管在 https://github.com/xudafeng/detect-port

联系方式:https://github.com/xudafeng/ 可以跟帖或者直接在 github 提出 issue。

欢迎大家使用并提出问题和建议,我们会积极跟进和修改,谢谢!

共收到 2 条回复 时间 点赞

请教一下,callback 里的 error 参数是用来做什么的?
在你的例子里只看到通过判断 _port 与传入参数是否一致来判断端口是否可用,但没看到 error 参数的使用。

#1 楼 @chenhengjie123 error 参数是 node 的默认写法,因为这个探测端口的操作是一个异步 io 操作,如果过程中发生错误的话,这个 error 的值就不会为空,一般会先进行错误判断,我马上补充,谢谢指正。

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册