Unlock the Full Potential of Your Applications with get-port a Comprehensive Guide on APIs and Usage Examples

Introduction to get-port

The get-port package is a highly efficient and user-friendly Node.js module designed to identify available network ports. This is incredibly useful in situations where you need to run multiple services or applications on different ports without conflicts.

Dozens of Useful API Explanations with Code Snippets

Basic Usage


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

  (async () => {
    const port = await getPort();
    console.log(port);
    // Output: An available port number
  })();

Specifying a Port Range


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

  (async () => {
    const port = await getPort({port: getPort.makeRange(8000, 8100)});
    console.log(port);
    // Output: An available port number between 8000 and 8100
  })();

Preferred Port with Fallback


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

  (async () => {
    const port = await getPort({port: [3000, 3001, 3002]});
    console.log(port);
    // Output: 3000 if available, otherwise 3001, 3002, or another available port
  })();

Setting the Host


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

  (async () => {
    const port = await getPort({host: '127.0.0.1'});
    console.log(port);
    // Output: An available port that is accessible on host 127.0.0.1
  })();

Application Example with the Introduced APIs

Here’s how you can build a simple Express server which uses get-port to dynamically assign ports:


  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 http://localhost:${port}`);
    });
  })();

This example demonstrates how quick and easy it is to utilize get-port to run an Express server without port conflicts.

Integrate get-port into your workflow today and ensure your applications run smoothly and efficiently without the hassle of managing port conflicts manually!

Hash: ee7efab139d35a979f74af0fd7ad8b05b964d41e5ce285e9e43d47330b9fa1c0

Leave a Reply

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