Express.js | app.listen() Function
The app.listen() function is used to bind and listen the connections on the specified host and port. This method is identical to Node’s http.Server.listen() method.
If the port number is omitted or is 0, the operating system will assign an arbitrary unused port, which is useful for cases like automated tasks (tests, etc.).
app.listen([port[, host[, backlog]]][, callback])
Explanation of the syntax:
- (Optional) It specifies the port on which we want our app to listen.
- (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 above syntax, so this means port must be specified before specifying host and backlog).
- (Optional) It specifies the max length of queue of pending connections. You can specify the backlog if and only if you have already specifies port and host.( since you have a closing bracket after ([, backlog]), so this means you will have to specify host before specifying backlogs)
- (Optional) It specifies a function that will get executed, once your app starts listening to 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.
Installation of express module:
- You can visit the link to Install express module. You can install this package by using this command.
npm install express
- After installing express module, you can check your express version in command prompt using the command.
npm version express
- After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.
Steps to run the program:
- The project structure will look like this:
- Make sure you have installed express module using the following command:
npm install express
- Run index.js file using below command:
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.