What is portfinder?
The portfinder npm package is a utility for getting a port number that is guaranteed to be free on the current machine. It is useful for running servers on dynamically assigned ports to avoid conflicts.
What are portfinder's main functionalities?
Get an available port
This feature allows you to find an available port on the machine. The `getPort` function takes a callback that provides the port number.
const portfinder = require('portfinder');
portfinder.getPort((err, port) => {
if (err) {
throw err;
}
console.log('Available port found:', port);
});
Set the base port
Before calling `getPort`, you can set the `basePort` property to tell portfinder to start searching for a free port from a certain number.
const portfinder = require('portfinder');
portfinder.basePort = 3000;
portfinder.getPort((err, port) => {
if (err) {
throw err;
}
console.log('Available port found:', port);
});
Set the range of ports to search
You can specify a range of ports for portfinder to search within by providing an options object with `port` and `stopPort` properties.
const portfinder = require('portfinder');
portfinder.getPort({
port: 3000, // minimum port
stopPort: 3333 // maximum port
}, (err, port) => {
if (err) {
throw err;
}
console.log('Available port found:', port);
});
Other packages similar to portfinder
get-port
Similar to portfinder, get-port is a package that helps you get an available TCP port to listen on. Unlike portfinder, get-port returns a Promise and supports async/await syntax, which can be more convenient in modern Node.js applications.
detect-port
Detect-port is another package that checks for an available port on your machine. It is similar to portfinder but also allows you to check if a specific port is available and returns an alternative if it's not, which can be useful for suggesting the next available port.
node-portfinder
Installation
Installing npm (node package manager)
curl http://npmjs.org/install.sh | sh
Installing node-portfinder
$ [sudo] npm install portfinder
Usage
The portfinder
module has a simple interface:
var portfinder = require('portfinder');
portfinder.getPort(function (err, port) {
});
By default portfinder
will start searching from 8000
. To change this simply set portfinder.basePort
.
Run Tests
$ npm test