By Specifying Port in Code

We will specify the port explicitly in the code within the Node.js application. The server is then configured to listen in this predetermined port by setting and communicating the desired port for the application.

Syntax:

const port = 3000; // Specify the desired port
server.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

Example: In the below example, we have specified the predetermined port in the code which is set to 4000. So the node application is running on Port 4000.

Javascript




// app.js
 
const http = require('http');
// specifying the desired port
const port = 4000;
const server = http.createServer((req, res) => {
    // adding port information to the response
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end(`Hello, w3wiki! Server is running on port ${port}`);
});
server.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});


Output:

How to run Node/Express on a specific port?

Port in Node is the numerical endpoint that is assigned to the process to allow communication over the network. Each application is identified uniquely by using this port number. There are port numbers that range from 0 to 65535, some of the ports are already assigned to the common services. In this article, we are going to learn how we can run a node on a specific port rather than using the default port. We will run a node on a specific port by using the two approaches.

Similar Reads

Prerequisites

Node JS Express JS...

Steps to use middleware chaining in Express JS

Step 1: In the first step, we will create the new folder by using the below command in the VScode terminal....

Approach 1: By Specifying Port in Code

We will specify the port explicitly in the code within the Node.js application. The server is then configured to listen in this predetermined port by setting and communicating the desired port for the application....

Approach 2: Using Environment Variable

...