0
0
Expressframework~5 mins

Listening on a port in Express

Choose your learning style9 modes available
Introduction
Listening on a port lets your Express app accept requests from users or other programs. It opens a door for communication.
When you want your web app to be reachable on the internet or local network.
When testing your Express server locally to see how it responds.
When deploying your app so it can handle real user traffic.
When running multiple apps on different ports on the same machine.
When you want to specify a custom port instead of the default.
Syntax
Express
const express = require('express');
const app = express();

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});
The listen method starts the server and waits for connections on the given port.
The callback function runs once the server is ready, useful for logging.
Examples
Starts the server on port 3000 without a callback.
Express
app.listen(3000);
Starts the server and logs a message when ready.
Express
app.listen(3000, () => {
  console.log('Server started on port 3000');
});
Uses an environment variable for the port, with 3000 as fallback.
Express
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Listening on port ${PORT}`);
});
Sample Program
This program creates a simple Express server that responds with 'Hello, world!' when you visit the home page. It listens on port 3000 and logs a message when ready.
Express
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello, world!');
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});
OutputSuccess
Important Notes
Listening on a port is how your server accepts incoming requests.
If the port is already in use, the server will fail to start.
Common mistake: forgetting to call listen, so the server never starts.
Use environment variables for ports in real apps to avoid conflicts.
Summary
Listening on a port opens your app to receive requests.
Use app.listen(port, callback) to start the server.
Always handle the callback to confirm the server started.