Open In App

Express app.listen() Function

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:

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:

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.




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.

Article Tags :