Node.js ยท Chapter 13 of 43

Creating a Server

Building on the http module, a Node.js server listens on a port and responds to incoming client requests, such as web browsers or API clients.

Once a server is listening, it stays running, handling requests one after another using the event loop.

Listening on a port

`server.listen(port, callback)` starts the server and optionally logs a confirmation once it's ready.

Handling different requests

Inside the request handler, you inspect `req.url` and `req.method` to decide how to respond differently to different requests.

Example 1 (javascript)
const http = require('http');
const server = http.createServer((req, res) => {
  console.log(req.method, req.url);
  res.end('OK');
});
server.listen(3000, () => console.log('Listening on port 3000'));
Output
Listening on port 3000
GET /

The server logs each request's method and URL, then responds with 'OK'.

Example 2 (javascript)
server.listen(3000, '127.0.0.1', () => {
  console.log('Server bound to localhost');
});
Output
Server bound to localhost

You can also specify a hostname to bind the server to.

Key points

  • server.listen() starts the server on a given port.
  • req.url and req.method identify what the client requested.
  • The server keeps running and handling requests via the event loop.
  • You can bind a server to a specific hostname/IP.
๐Ÿ’ก Note: Common ports for development are 3000, 5000, and 8080.

๐Ÿ“ Quick Quiz

1. Which method starts a server listening for requests?

2. Which property tells you the request path?

3. What keeps a Node.js server running to handle multiple requests?