Comprehensive Get Port Guide API Examples and Code Snippets for Optimal SEO

Introduction to get-port

get-port is a highly useful and efficient package for discovering available ports in your Node.js applications. It helps in dynamically finding an unused port number, making the development process faster and more convenient.

Basic Usage

To get started with get-port, first, you need to install it:

  npm install get-port

Then, you can use it as follows:

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

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

Specifying a Range

You can specify the range or specific ports you want get-port to search from:

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

  (async () => {
    const port = await getPort({ port: getPort.makeRange(3000, 3100) });
    console.log(port); // Will find a port between 3000 to 3100
  })();

Multiple Ports

Requesting multiple ports:

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

  (async () => {
    const ports = await Promise.all([
      getPort(),
      getPort(),
      getPort()
    ]);
    console.log(ports); // [Port1, Port2, Port3]
  })();

Setting a Specific Hostname

You can search for a port on a specific hostname:

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

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

App Example

Let’s create a simple HTTP server using get-port to obtain an available port:

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

  (async () => {
    const port = await getPort();

    const requestHandler = (request, response) => {
      response.end('Server running on port ' + port);
    };

    const server = http.createServer(requestHandler);

    server.listen(port, (err) => {
      if (err) {
          return console.log('Something bad happened', err);
      }

      console.log(`Server is listening on ${port}`);
    });
  })();

In this example, get-port finds an available port for our HTTP server, ensuring it will not conflict with other processes.

Hash: ee7efab139d35a979f74af0fd7ad8b05b964d41e5ce285e9e43d47330b9fa1c0

Leave a Reply

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