Open In App

Express app.listen() Function

Improve
Improve
Like Article
Like
Save
Share
Report

app.listen() in Express is like telling your app to start listening for visitors on a specific address and port, much like how Node listens for connections. The app, created by `express()`, is just a handy function that handles different types of requests, making it easy to serve both HTTP and HTTPS versions of your app without extra complexity.

Syntax: 

app.listen([port[, host[, backlog]]][, callback])

Parameters:

  • Port: It specifies the port on which we want our app to listen.
  •  Host (Optional): It specifies the IP Address of the host on which we want our app to listen. You can specify the host if and only if you have already specified the port. ( since you have a closing(‘]’) bracket after ([, host[, backlog]]) as you can see in the above syntax, so this means the port must be specified before specifying host and backlog).
  • Backlog (Optional): It specifies the max length of the queue of pending connections. You can specify the backlog if and only if you have already specified the port and host. ( since you have a closing bracket after ([, backlog]), so this means you will have to specify the host before specifying backlogs)
  • Callback (Optional):  It specifies a function that will get executed, once your app starts listening to the specified port. You can specify callback alone i.e., without specifying port, host, and backlogs.( since this is a separate set of arguments in opening and closing brackets([, callback]), this means you can specify these arguments without specifying the argument of previous opening and closing square brackets.

Steps to Install the express module:

Step 1: You can install this package by using this command.

npm install express

Step 2: After installing the express module, you can check your express version in the command prompt using the command.

npm version express

Project Structure:

NodeProj

Project Structure

The updated dependencies in package.json file will look like:

"dependencies": {
"express": "^4.18.2",
}

Example 1: Below is the code of app.listen() Function implementation.

Javascript




const express = require('express');
const app = express();
const PORT = 3000;
 
app.listen(PORT, function(err){
    if (err) console.log("Error in server setup")
    console.log("Server listening on Port", PORT);
})


Steps to run the program: 

Run the index.js file using the below command: 

node index.js

Output:  

Server listening on Port 3000

So this is how you can use the Express app.listen() function which Binds and listens for connections on the specified host and port.


Last Updated : 01 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads