Comprehensive Get Port Usage Guide and API Examples to Boost Your Application Development

Introduction to get-port

The get-port module is a highly efficient tool designed to help developers find available network ports. It’s a powerful utility that ensures your applications bind only to free ports, thus avoiding conflicts. This article will delve deep into the various API methods of get-port and provide comprehensive examples to enhance your understanding and application.

Installation

npm install get-port

Basic Usage

const getPort = require('get-port');

(async () => {
    const port = await getPort();
    console.log(port);
})();

Setting Port Ranges

Sometimes you may want to search for a free port within specific ranges. get-port allows you to specify a range of ports.

const getPort = require('get-port');

(async () => {
    const port = await getPort({port: getPort.makeRange(3000, 3100)});
    console.log(port);
})();

Setting Multiple Preferred Ports

You can specify multiple preferred ports. The first port to be available will be returned.

const getPort = require('get-port');

(async () => {
    const port = await getPort({port: [3000, 3001, 3002]});
    console.log(port);
})();

Using a Port with a Hostname

You can also specify a hostname with the desired port.

const getPort = require('get-port');

(async () => {
    const port = await getPort({host: 'localhost', port: 8080});
    console.log(port);
})();

Using with Express.js

Here’s an example of how you can use get-port with an Express.js application:

const express = require('express');
const getPort = require('get-port');

(async () => {
    const app = express();
    const port = await getPort({port: getPort.makeRange(3000, 3100)});

    app.get('/', (req, res) => {
        res.send('Hello World!');
    });

    app.listen(port, () => {
        console.log(`Server is running on port ${port}`);
    });
})();

Hash: ee7efab139d35a979f74af0fd7ad8b05b964d41e5ce285e9e43d47330b9fa1c0

Leave a Reply

Your email address will not be published. Required fields are marked *