Node.js
app.listen
Learn to start the server with app.listen.
app.listen
app.listen(port, callback) starts the server listening on a given port. Until this call is made, the Express application does not accept requests. The second parameter is a callback called when the server starts.
Example: app.listen(3000, () => console.log("Server started"));. This starts listening on port 3000 and prints Server started when ready. The app.listen callback usually prints a confirmation message, so you know the server is ready. Common ports in development are 3000, 8000, 8080; in production 80 (HTTP) or 443 (HTTPS). Express calls http.createServer behind the scenes; you do not deal with it directly.
Starting the server
After app.listen is called, Express listens for incoming requests on the specified port. Each request is matched against your routes and the appropriate handler is called.
Example: const server = app.listen(3000, () => console.log("Server started"));. app.listen returns a server object; you can assign it to a server variable. With server.close() you stop the server. This is useful in tests or temporary servers. During development the server keeps running; you stop it from the terminal with Ctrl+C. Even with many routes, a single app.listen starts the whole application.
Exercise Start the server
Import express and create app. Define a route with app.get("/", (req, res) => res.send("Running")). Start the server with const server = app.listen(3000, () => console.log("Server started")). The ready-made code below sends a request and prints the result.
Show example solution
const express = require("express");
const app = express();
app.get("/", (req, res) => res.send("Running"));
const server = app.listen(3000, () => console.log("Server started"));
setTimeout(() => {
const http = require("http");
http.get("http://localhost:3000/", (res) => {
let body = "";
res.on("data", (c) => body += c);
res.on("end", () => { console.log("Reply: " + body); server.close(); });
});
}, 100);
Test yourself
-
Complete the app.listen call
app.____(3000, () => console.log("Sunucu başladı"));
Show answer
app.listen(3000, () => console.log("Sunucu başladı"));
-
Match each piece to its role
- app.listen
- Starts the server
- port (3000)
- Port number
- callback
- Called when server starts
- server.close
- Stops the server
-
What is the second parameter of app.listen?
app.listen(3000, ?)
- A port number
- Bir rota yolu
- A module name
- A callback called when the server starts
Show answer
A callback called when the server starts — The second parameter is a callback.
Next lesson: Summary - Express basics