Node.js端口扫描器

发布于:2021-02-15 00:00:58

0

291

0

Nodejs 端口 扫描程序

Node.js已经成为创建服务或充当服务的实用工具的不可思议的工具。通常是npm start,等一下,你会看到这个实用程序提供了一个地址和端口;一个很好的例子是localhost:8000。关于此模式,让我感到困扰的一件事是,如果您有许多基于服务的实用程序,您最终会遇到“正在使用的端口”错误,然后您需要查看所有的实用程序,以确定应该关闭哪一个。

有一个简单的解决方案:   Node Port Scanner。该实用程序提供查找给定主机上正在使用或可用端口的方法!

使用端口扫描器

解决端口冲突的最常见用例是findAPortNotInUse:

var portscanner = require('portscanner');

// 127.0.0.1 is the default hostname; not required to provide
portscanner.findAPortNotInUse([3000, 3010], '127.0.0.1').then(port => {
  console.log(`Port ${port} is available!`);

  // Now start your service on this port...
});

提供一系列端口,然后从第一个可用端口开始很简单-不再发生冲突。

您还可以检查给定端口的状态,或检查正在使用的端口:

// Get port status
portscanner.checkPortStatus(3000, '127.0.0.1').then(status => {
  // Status is 'open' if currently in use or 'closed' if available
  console.log(status);
});

// Find port in use
portscanner.findAPortInUse([3000, 3005, 3006], '127.0.0.1').then(port => {
  console.log('PORT IN USE AT: ' + port);
});

使用此端口扫描程序实用程序非常简单,并且是使服务在任何可用端口上运行的最简单方法。不必要的硬编码端口使用只会导致失败!