What is detect-port?
The detect-port npm package is a utility for detecting available network ports on a machine. It is useful for scenarios where you need to find an open port to start a server or service.
What are detect-port's main functionalities?
Detecting an available port
This feature allows you to check if a specific port is available. If the port is occupied, it suggests an alternative available port.
const detect = require('detect-port');
const port = 3000;
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}`);
}
});
Promise-based port detection
This feature provides a promise-based approach to detect an available port, making it easier to integrate with modern JavaScript code that uses async/await.
const detect = require('detect-port');
const port = 3000;
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);
});
Other packages similar to detect-port
portfinder
The portfinder package is another utility for finding open ports. It offers similar functionality to detect-port but includes additional features like specifying a range of ports to search within. It is also promise-based and has a more extensive API.
get-port
The get-port package is a lightweight utility for finding an available port. It is similar to detect-port but focuses on simplicity and ease of use. It is promise-based and allows specifying a preferred port or a range of ports.
detect-port
port detector
Installment
$ npm i detect-port -g
Quick Start
# 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
Use As Module
var detect = require('detect-port');
detect(port, function(error, _port) {
if (port === _port) {
console.log('port: %d was not occupied', port);
} else {
console.log('port: %d was occupied, try port: %d', port, _port);
}
});
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);
}
})();
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);
}
});
Clone and Run test
# clone from git
$ git clone git://github.com/xudafeng/detect-port.git
$ cd detect-port
# install dependencies
$ make install
# test and coverage
$ make test
License
MIT
Copyright (c) 2015 xdf