ArticleZip > Nodejs How To Get The Servers Port

Nodejs How To Get The Servers Port

Node.js is a powerful platform for building server-side applications using JavaScript. One essential piece of information you often need when working with Node.js is the port on which your server is running. In this guide, we will walk through the steps to retrieve the server's port in Node.js.

When you run a Node.js server, it typically listens on a specific port to handle incoming requests. To find out which port your server is using, you can access the port number from the server object.

Javascript

const http = require('http');
const server = http.createServer((req, res) => {
  res.end('Hello World!');
});

const port = server.address().port;

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

In this code snippet, we create a simple HTTP server using the `http` module in Node.js. We then access the server's port using the `server.address().port` expression. By logging the port to the console, you can see which port the server is listening on.

Another way to get the server's port is by checking the environment variables provided by the system. When you deploy your Node.js application to a production environment, the hosting platform often assigns a port number dynamically using environment variables. You can access this port using the `process.env.PORT` variable.

Javascript

const port = process.env.PORT || 3000;

In this example, we use the `process.env.PORT` variable as the server's port, falling back to the default port `3000` if the environment variable is not set. This approach allows your application to adapt to different environments without hardcoding the port number.

Additionally, if you are using a framework like Express.js to build your Node.js server, retrieving the port is even simpler. Express automatically sets the port value for you, making it accessible through the `app.get('port')` method.

Javascript

const express = require('express');
const app = express();

const port = app.get('port');

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

In this code snippet, we create an Express application and use the `app.get('port')` method to retrieve the port number set by Express. This streamlined approach simplifies the process of getting the server's port in an Express application.

By following these methods, you can easily retrieve the server's port in your Node.js applications. Whether you are working with basic HTTP servers or sophisticated Express frameworks, knowing the server's port is essential for monitoring and managing your application's network connections.

×