
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Express.js App Listen Method
The app.listen() method binds itself with the specified host and port to bind and listen for any connections. If the port is not defined or 0, an arbitrary unused port will be assigned by the operating system that is mainly used for automated tasks like testing, etc.
The app object returned by express() is a JavaScript function, that is passed to Node’s HTTP servers as a callback which handles the requests. This makes the application to provide both HTTP and HTTPS versions of the same app with the same code base, as the app does not inherit from these.
Syntax
app.listen([port], [host], [backlog], [callback])
Example 1
Create a file with the name "appListen.js" and copy the following code snippet. After creating the file, use the command "node appListen.js" to run this code.
// app.listen() Method Demo Example // Importing the express module var express = require('express'); // Initializing the express and port number var app = express(); // Initializing the router from express var router = express.Router(); var PORT = 3000; // App listening on the below port app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
Output
C:\home
ode>> node appListen.js Server listening on PORT 3000
Example 2
Let’s take a look at one more example.
// app.listen() Method Demo Example // Importing the express module var express = require('express'); // Initializing the express and port number var app = express(); // Initializing the router from express var router = express.Router(); // Assigning a port that is already in use var PORT = 80; // App listening on the below port app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
Output
C:\home
ode>> node appListen.js Server listening on PORT 80